Compare commits

...
3 Commits
  • fix(routing): restore room creation after relay disconnects
    Fix a room-creation stall caused by repeated publication attachment attempts, and preserve healthy relay subtrees when capacity is reduced. This maintenance update also fixes two UI details and clarifies audio troubleshooting.
    
    ## Release notes
    
    **Piik, now in your pocket.**
    
    Piik App supports Android screen sharing, with touch controls for a friend's computer.
    
    **手机,也能开播。**
    
    Piik App 支持 Android 屏幕分享,也能用手机控制朋友的电脑。
    
    ### English
    
    This maintenance update restores room creation after an interrupted relay connection and improves relay-limit changes and controls.
    
    - Fix a disconnected relay causing room creation and routing to become unresponsive (#536).
    - Preserve healthy relay subtrees when reducing capacity; move a feasible viewer before retiring the relay branch.
    - Keep resolution inputs focused when their values update, so editing can continue normally.
    - Keep participant headsets visible in both light and dark themes.
    - Clarify how virtual audio outputs affect screen-sharing sound and how to check the selected output device.
    
    Existing 2.x App/site compatibility and saved room data are preserved. Refresh open site pages after the update. App-local users need the updated App bundle for its included Web fixes. A hosted-service restart reconnects active rooms.
    
    ### 中文
    
    本次维护更新修复转发连接中断后无法创建房间的问题,并改善转发上限调整和控件操作。
    
    - 修复转发节点断线后,房间创建和线路分配可能卡住的问题(#536)。
    - 降低转发容量时保留正常的下游分支,优先迁移可迁移的观众,避免直接拆掉整条转发分支。
    - 修复分辨率数值更新时输入框失去焦点的问题,保持连续编辑。
    - 改善亮色与暗色主题下人物耳机状态的可见性。
    - 补充虚拟音频输出与屏幕共享声音的排查说明,帮助确认实际使用的输出设备。
    
    保留现有 2.x App/站点兼容性及已保存的房间数据。站点更新后请刷新已打开的页面;App 本地分享用户需更新 App,才能获得包内网页修复。托管服务重启时,活动房间会重新连接。
    
    ## Validation
    
    - `npm run check`: typecheck, 108 test files / 1953 tests, and the standard Web build passed on clean `e49b66497bf452268a3cb75a70d740fbe2eed072`.
    - Existing route, signal, Server and HTTP App Go package checks passed, including the #536 regression and capacity subtree cases.
    - The standard local Linux amd64 candidate from this revision passed archive/manifest/hash checks and actual execution on the owned Linux VM: configuration checks, health, served Web source identity, two create/authenticate/abandon cycles, and graceful shutdown. This was an explicitly identified development candidate; final v2.6.2 packages remain the release pipeline's output.
    - Actual maintenance-branch component previews confirmed resolution input DOM identity/focus after external updates and headset visibility in both themes, including mute/deafen states.
    
    No native platform matrix was rerun for these changes.
    
    ## Impact
    
    Browser/server v24, Native control v10, capture v7 and SQLite schema 2 are unchanged. Deployment uses the existing atomic wrapper and scoped postflight; it does not change proxy, firewall or persistence configuration.
  • fix(release): resume pending mirrors from original artifacts
    ## Problem and outcome / 问题与结果
    
    An otherwise published release could leave its AtomGit downloads incomplete when the platform had not yet synchronized its Git tag, or when a larger package exceeded the upload deadline. Recovery previously required a manual workflow run.
    
    The existing mirror workflow now checks every three hours and after CI completion. It only resumes the latest published release, locates its original CI artifacts, and retains the existing full-download checksum verification. Complete or deferred mirrors use a sparse tooling checkout and skip dependency installation and artifact downloads. Git synchronization remains entirely with AtomGit; publication waits for the matching synchronized commit and tag and never creates or changes Git references.
    
    Increase only the signed upload deadline from three to ten minutes, following the observed 51 MB APK timeout. Metadata/read timeouts, retry counts and the workflow's 30-minute limit remain unchanged.
    
    ## Verification / 验证
    
    - 58 focused mirror/publisher tests, TypeScript, documentation and diff checks passed.
    - Actual AtomGit readiness was checked against the v2.6.1 source and tag. Fixtures include the provider's four automatic source archives and distinguish them from uploaded packages.
    - The release planner returns `publish: false`. This workflow resumes existing verified packages and performs no software build.
    
    ## Impact / 影响
    
    Release automation only. Source synchronization belongs to AtomGit; Release and attachment completion belong to this workflow. Missing original artifacts or conflicting source identities remain explicit failures and never cause a published version to be rebuilt or overwritten.
  • fix(release): inspect the requested container platform
    ## Problem and outcome / 问题与结果
    
    When Docker retains both platforms for a multi-platform tag, an image inspection without a platform selects the host architecture. The v2.6.1 publisher consequently inspected AMD64 after pulling ARM64 and stopped before updating `latest`.
    
    Inspect the requested platform explicitly. The publisher test now models a store that retains both variants, so it catches this failure instead of assuming the last pull replaces the tag's architecture.
    
    ## Verification / 验证
    
    - The corrected model reproduced the failure before the change; all 17 publisher tests pass with the fix.
    - TypeScript and diff checks pass.
    - Independent registry checks verified both published v2.6.1 configurations, their source/package identities, and all referenced blobs. Recovery moved the existing index bytes to `latest` without rebuilding packages or replacing the version tag.
    
    ## Impact / 影响
    
    Publication tooling only. The release planner returns `publish: false`; this does not create another product version or change v2.6.1 artifacts.
22 changed files with 530 additions and 32 deletions

No files matched your search

+20 -5
View File
@@ -1,6 +1,8 @@
name: AtomGit mirror
on:
schedule:
- cron: '17 */3 * * *'
workflow_run:
workflows: [CI]
types: [completed]
@@ -8,8 +10,8 @@ on:
workflow_dispatch:
inputs:
run_id:
description: Original CI run that published the current GitHub release
required: true
description: Original CI run (optional; otherwise find the current published source)
required: false
type: string
permissions:
@@ -25,7 +27,7 @@ jobs:
mirror:
if: >-
github.repository == 'TNTcraftHIM/Piik' && github.ref == 'refs/heads/main' &&
(github.event_name == 'workflow_dispatch' ||
(github.event_name == 'workflow_dispatch' || github.event_name == 'schedule' ||
(github.event.workflow_run.event == 'push' &&
github.event.workflow_run.head_branch == 'main'))
runs-on: ubuntu-latest
@@ -35,17 +37,30 @@ jobs:
- uses: actions/checkout@v6
with:
persist-credentials: false
sparse-checkout-cone-mode: false
sparse-checkout: |
/scripts/
/package.json
/package-lock.json
/.node-version
- uses: actions/setup-node@v6
with:
node-version-file: .node-version
cache: npm
- name: Check mirror readiness without build dependencies
id: readiness
run: node scripts/release-mirror-ready.mjs
env:
GH_TOKEN: ${{ github.token }}
- run: npm ci --ignore-scripts
if: steps.readiness.outputs.status == 'ready'
- name: Resolve the published source
id: source
if: steps.readiness.outputs.status == 'ready'
run: node scripts/release-mirror-source.mjs "$PIIK_SOURCE_RUN_ID"
env:
GH_TOKEN: ${{ github.token }}
PIIK_SOURCE_RUN_ID: ${{ inputs.run_id || github.event.workflow_run.id }}
PIIK_SOURCE_RUN_ID: ${{ inputs.run_id }}
- name: Download original Server artifacts
if: steps.source.outputs.mirror == 'true'
uses: actions/download-artifact@v8
@@ -77,6 +92,6 @@ jobs:
- name: Explain recovery
if: failure() && steps.source.outputs.mirror == 'true'
run: |
printf 'Mirror failed; GitHub publication and Website are independent. Retry this workflow with original CI run %s. If artifacts expired, recover the retained original build output; do not rebuild this version. See docs/operations/github.md.\n' "$PIIK_SOURCE_RUN_ID" >> "$GITHUB_STEP_SUMMARY"
printf 'Mirror failed; the scheduled check will retry from original CI run %s. GitHub publication and Website are independent. If artifacts expired, recover the retained original build output; do not rebuild this version. See docs/operations/github.md.\n' "$PIIK_SOURCE_RUN_ID" >> "$GITHUB_STEP_SUMMARY"
env:
PIIK_SOURCE_RUN_ID: ${{ steps.source.outputs.run_id }}
+6
View File
@@ -437,6 +437,12 @@ for current setup details.
3. Camera video and microphone inputs are selected separately. For a built-in
camera microphone or OBS audio, see [camera and audio inputs](./sharing.md#cameras-and-virtual-audio-inputs).
With a virtual mixer or several output devices, check where the app sends its
sound. Without application exclusion, Windows App screen capture reads the
default playback device. Select the app's window to capture its process audio,
or route its sound to that default
device before restarting screen sharing.
### Cannot hear someone speaking
For speech added through **Include my microphone**, check the picture's
+4
View File
@@ -359,6 +359,10 @@ Windows 需要用户授权;其他采集要求显示边框时,边框仍会保
2. 房主应选择支持分享声音的来源,并在选源器中打开声音;可用声音取决于来源和平台。
3. 摄像头画面与麦克风输入分别选择。内置麦克风或 OBS 音频的用法,见[摄像头与音频输入](./sharing.zh-CN.md#摄像头与虚拟音频输入)。
使用虚拟混音器或多个输出设备时,先检查应用把声音送到了哪里。未启用应用声音排除时,
Windows App 的屏幕采集使用默认播放设备;可以改选该应用的窗口来采集程序声音,
或把应用声音送到默认播放设备后重新分享屏幕。
### 听不到说话声
如果房主使用 **分享麦克风**,先检查画面的[来源声音](#有画面但没有来源声音),
+28 -5
View File
@@ -94,24 +94,47 @@ Image checks, version identity and retries follow
source and Release mirror. GitHub owns development, issues and original packages.
AtomGit's configured repository synchronization handles branches, tags and commits;
the **AtomGit mirror** GitHub workflow separately copies published binary assets.
Git synchronization remains AtomGit's responsibility; this workflow does not push,
create or change Git references, and does not ask users to synchronize them manually.
Its repository Actions secret is `ATOMGIT_TOKEN`. Never put this token in source,
a remote URL or a distributed package. GitHub publication keeps its scoped token.
After a completed main-push CI run, the workflow checks whether that run published
the current stable GitHub release. A later failed container step does not prevent
mirroring already-published packages. It downloads the matching run's complete
After a completed main-push CI run, the workflow checks the current stable GitHub
release and finds its original publishing CI run, even when the triggering run
only updated tooling. A later failed container step does not prevent
mirroring already-published packages. It downloads the source run's complete
original Server and App artifacts and invokes `scripts/mirror-release.mjs`.
Runs without the current published release are skipped. GitHub publication
and **Website** do not depend on mirror success. An unfinished mirror remains a
GitHub publication and **Website** do not depend on mirror success. An unfinished mirror remains a
prerelease until every package passes anonymous full-download SHA-256 validation.
This includes the original signed APK and its already-built ZIP wrapper.
Every three hours the same workflow also checks the latest GitHub release's mirror
metadata. A stable mirror with the matching source marker and complete package
inventory of uploaded attachments needs no further work; provider-generated source
archives do not count as packages. A missing source commit or matching tag is
reported as deferred until AtomGit's scheduled Git synchronization completes.
Both outcomes use a sparse tools-only checkout and skip dependency installation
and artifact downloads. API failures
or conflicting source identities remain failures, not successful deferrals.
When ready, recovery locates the completed main-push CI run for that exact source,
downloads its original artifacts and resumes the existing publisher. It never
builds software. The publisher verifies every package anonymously before marking
the mirror stable; the periodic metadata check reuses that completion boundary.
Expired original artifacts require retained original build output, not rebuilding
the same published version. A stable release missing packages is an explicit
integrity failure and is never silently replaced.
For recovery, rerun **AtomGit mirror** with the original publishing CI run ID:
```sh
gh workflow run atomgit-mirror.yml --repo TNTcraftHIM/Piik --ref main -f run_id=RUN_ID
```
The run ID is optional for a manual status check; without it, the workflow uses
the same latest-release lookup as its scheduled check. Ordinary delayed source
synchronization or interrupted uploads need no manual trigger.
The source must be a completed main-push CI run matching the latest published
GitHub release. The workflow runs trusted main tooling and treats artifacts only
as data. A superseded release cannot complete a new mirror. Both publishers reject
+11
View File
@@ -8,6 +8,17 @@
## Windows Audio Exclusion
Default display capture reads the current default render endpoint; process
inclusion/exclusion uses Windows'
[endpoint-independent loopback](https://learn.microsoft.com/en-us/samples/microsoft/windows-classic-samples/applicationloopbackaudio-sample/).
For [#534](https://github.com/TNTcraftHIM/Piik/issues/534), an isolated API control
sent two tones only to an existing virtual endpoint without changing the default
headset. Default capture returned no packets; excluding a silent test process
received both tones. The real Go session also retained video and audio-output
ownership through repeated exclusion/clear/off/on changes. The reporter's actual
playback endpoint and first failing transition remain the next discriminator;
these controls do not identify an exclusion-state leak.
A Windows 11 build 26200 check used two independent WinMM processes emitting
500 Hz and 1500 Hz tones, through the production capture helper and Go PCM
reader. Default-device loopback captured both at approximately 1799 amplitude;
+6 -1
View File
@@ -1,12 +1,17 @@
# Current TODO Ledger
Last reviewed: 2026-11-07
Last reviewed: 2026-11-09
This ledger contains unfinished work and explicit owner holds. Product modules
own behavior; research and Git/PRs own evidence and completed history.
## Now
- [ ] **Windows sound only works with exclusion (#534).** Compare the affected
application's playback endpoint with Piik's default-endpoint capture. The
[audio scope control](./research/native-client-media.md#windows-audio-exclusion)
reproduces the contrast with another output device; locate the reporter's
first failing transition before changing the capture owner.
- [ ] **Blue-tinted sharing (#529).** Identify the source and affected receive
path from [#529](https://github.com/TNTcraftHIM/Piik/issues/529): Piik version,
platform, capture choice and matching source/Viewer screenshots. Compare
+32 -5
View File
@@ -461,22 +461,49 @@ func (c *Controller) availableViewers(includeBlocked bool) []*participant {
return viewers
}
// overflowChildren visits parents in participant order and returns each
// parent's overflowing children newest first.
// overflowChildren returns movable excess work in parent/newest order.
// Only when no overloaded parent has a movable child does it return the
// original newest-overflow failure work, before attempt ordering is applied.
func (c *Controller) overflowChildren() []string {
result := []string{}
fallback := []string{}
for _, parent := range c.participants.Values() {
overflowing := c.overflowPeerChildren(parent.peerID)
if len(overflowing) == 0 {
continue
}
movable := []string{}
for _, id := range c.childrenOf(parent.peerID) {
edge, _ := c.upstreamByViewer.Get(id)
child, _ := c.participants.Get(id)
if edge.PhysicalActive && child != nil && child.sessionID != "" && !child.departureConfirmed &&
len(c.buildCandidates(id, false)) > 0 {
movable = append(movable, id)
}
}
if len(movable) > 0 {
sort.SliceStable(movable, func(i, j int) bool {
left, _ := c.participants.Get(movable[i])
right, _ := c.participants.Get(movable[j])
return compareParticipant(right, left) < 0
})
result = append(result, movable...)
continue
}
overflow := []string{}
for _, id := range c.overflowPeerChildren(parent.peerID) {
for _, id := range overflowing {
child, _ := c.participants.Get(id)
if child != nil && child.sessionID != "" && !child.departureConfirmed && !c.participantBlocked(child) {
overflow = append(overflow, id)
}
}
slices.Reverse(overflow)
result = append(result, overflow...)
fallback = append(fallback, overflow...)
}
return result
if len(result) > 0 {
return result
}
return fallback
}
// overflowPeerChildren keeps the oldest physically active direct children
+7 -1
View File
@@ -115,7 +115,7 @@ func (c *Controller) startPublicationAttach(nowMs int64) bool {
}
tuple.Publication = PublicationReuse
}
c.operation = &operation{
op := &operation{
childPeerID: childID, childSessionID: child.sessionID,
demandPeerID: childID, demandSessionID: child.sessionID,
reason: DemandPublicationAttach, baseRevision: c.revision,
@@ -123,6 +123,12 @@ func (c *Controller) startPublicationAttach(nowMs int64) bool {
videoGeneration: c.videoGeneration, attachConnectionID: edge.ConnectionID,
candidates: []CandidatePlan{{Tuple: tuple, EndpointTransition: EndpointTransition{Kind: TransitionNone}}},
}
// A retained physical path may outlive its parent's signaling session.
// Select only attachments that can pass the same ownership check at begin.
if !c.publicationAttachOwned(op) {
continue
}
c.operation = op
return true
}
return false
+30
View File
@@ -2,6 +2,36 @@ package route
import "testing"
func TestPublicationAttachmentWaitsForItsParentSessionWithoutBlockingOtherBranches(t *testing.T) {
routes := voiceTree(t)
routes.SetDefaultCapacity(2, ms(9))
routes.UpsertParticipant(hostInput("host_session", 2), ms(9))
addViewer(routes, C, 0, ms(10))
commitRoomPeer(t, routes, 11, "voice-c")
before := routes.Snapshot()
routes.SetVideoPublication("share", false, 20)
a := beginVideoAttach(t, routes, 21, A, "video-a")
eq(t, routes.CandidateReady(a, 22, nil, CandidateProof{VideoGeneration: "share"}).Committed, true)
routes.DisconnectSession(A, sessionOf(A))
// A's proven physical path survives signaling grace, but it cannot own a
// new attachment for B until its signaling session returns. C is independent.
c := beginVideoAttach(t, routes, 23, C, "video-c")
eq(t, routes.CandidateReady(c, 24, nil, CandidateProof{VideoGeneration: "share"}).Committed, true)
for _, at := range []int64{25, 26, 50_000} {
noOperation(t, routes.Reconcile(at).Operation)
}
for _, child := range []string{A, B, C} {
previous, _ := before.UpstreamByViewer.Get(child)
edge := edgeOf(t, routes, child)
eq(t, edge.ConnectionID, previous.ConnectionID)
eq(t, edge.Usable && edge.PhysicalActive, true)
}
routes.UpsertParticipant(viewerInput(A, "resumed-a", 1), ms(50_001))
b := beginVideoAttach(t, routes, 50_002, B, "video-b")
eq(t, routes.CandidateReady(b, 50_003, nil, CandidateProof{VideoGeneration: "share"}).Committed, true)
noOperation(t, routes.Reconcile(50_004).Operation)
}
func TestRoomVideoRecoveryPreservesLogicalConnection(t *testing.T) {
routes := voiceTree(t)
routes.SetVideoPublication("share", false, 10)
@@ -100,6 +100,133 @@ func TestRelayVolunteerTwentyChildPhysicalOverlapRequiresOptIn(t *testing.T) {
}
}
func TestCapacityReductionMovesFeasibleLeafBeforeRetiringRelaySubtree(t *testing.T) {
join := func(t *testing.T, routes *Controller, id string, capacity int) {
t.Helper()
addViewer(routes, id, capacity, ms(1))
must(t, routes.Reconcile(2).Operation)
commitCurrent(t, routes, 3, id+"-connection")
}
for _, outcome := range []string{"commit", "failed-candidate", "exhausted-candidates", "all-unavailable", "multi-parent"} {
t.Run(outcome, func(t *testing.T) {
routes := newController(3, Options{QualityConvergenceEnabled: true,
NatPredictionEnabled: outcome == "multi-parent"})
if outcome == "multi-parent" {
routes.SetEffectiveCapacity(HOST, "host_session", 1, nil)
join(t, routes, A, 1)
join(t, routes, C, 0)
routes.SetEffectiveCapacity(HOST, "host_session", 2, nil)
join(t, routes, B, 2)
join(t, routes, D, 0)
addViewer(routes, E, 1, ms(1))
eq(t, must(t, routes.Reconcile(2).Operation).ChildPeerID, E)
prepared := beginOperation(t, routes, BeginInput{NowMs: 3,
ConnectionID: "first-nat-attempt", Reservation: direct()})
eq(t, routes.CandidateFailed(guardFor(E, prepared.Current.Revision, "first-nat-attempt"), 4).Accepted, true)
must(t, routes.Reconcile(5).Operation)
commitCurrent(t, routes, 6, E+"-connection")
routes.SetEffectiveCapacity(C, sessionOf(C), 1, nil)
eq(t, edgeOf(t, routes, C).ParentPeerID, A)
eq(t, edgeOf(t, routes, D).ParentPeerID, B)
eq(t, edgeOf(t, routes, E).ParentPeerID, B)
// A spent C->E opportunity cannot justify retiring C before
// another overloaded parent's live child can move under it.
routes.consumeCandidateOpportunity(C, *routes.planCandidate(C, peerTuple(E)))
for _, parent := range []string{C, E} {
routes.consumeCandidateOpportunity(D, *routes.planCandidate(D, peerTuple(parent)))
}
routes.SetEffectiveCapacity(A, sessionOf(A), 0, ms(10))
routes.SetEffectiveCapacity(B, sessionOf(B), 1, ms(10))
eq(t, len(routes.buildCandidates(C, false)), 0)
// The feasible child has more past attempts: the existing NAT
// sort must not promote another parent's unavailable fallback.
eq(t, routes.viewerAttemptsStarted(E) > routes.viewerAttemptsStarted(C), true)
result := routes.Reconcile(11)
eq(t, len(result.FailedPeerIDs), 0)
op := must(t, result.Operation)
eq(t, op.ChildPeerID, E)
eq(t, op.Candidates[0].Tuple.ParentPeerID, C)
deadline := op.DeadlineAtMs
eq(t, must(t, routes.Reconcile(12).Operation).DeadlineAtMs, deadline)
for _, child := range []string{A, B, C, D, E} {
eq(t, edgeOf(t, routes, child).PhysicalActive, true)
}
commitCurrent(t, routes, 13, "other-parent-to-live-subtree")
eq(t, edgeOf(t, routes, E).ParentPeerID, C)
eq(t, routes.physicalCopies(B), 1)
eq(t, edgeOf(t, routes, C).PhysicalActive, true)
return
}
// The ordinary join path reaches Host->{A,B,C}, C->D. Only D has
// a spare slot; C cannot move under its own descendant.
for _, viewer := range []struct {
id string
capacity int
}{{A, 0}, {B, 0}, {C, 1}, {D, 1}} {
join(t, routes, viewer.id, viewer.capacity)
}
eq(t, edgeOf(t, routes, D).ParentPeerID, C)
if outcome == "all-unavailable" {
routes.SetEffectiveCapacity(D, sessionOf(D), 0, ms(9))
}
routes.SetEffectiveCapacity(HOST, "host_session", 2, ms(10))
result := routes.Reconcile(11)
if outcome == "all-unavailable" {
noOperation(t, result.Operation)
eq(t, len(result.FailedPeerIDs), 2)
eq(t, result.FailedPeerIDs[0], C)
eq(t, result.FailedPeerIDs[1], D)
eq(t, edgeOf(t, routes, C).PhysicalActive, false)
eq(t, edgeOf(t, routes, D).PhysicalActive, false)
return
}
op := must(t, result.Operation)
eq(t, op.Reason, DemandCapacityReduction)
eq(t, op.ChildPeerID, B) // Newest feasible leaf still leads.
eq(t, op.Candidates[0].Tuple.ParentPeerID, D)
deadline := op.DeadlineAtMs
if outcome == "failed-candidate" || outcome == "exhausted-candidates" {
prepared := beginOperation(t, routes, BeginInput{NowMs: 12,
ConnectionID: "failed-leaf", Reservation: direct()})
eq(t, routes.CandidateFailed(guardFor(B, prepared.Current.Revision, "failed-leaf"), 13).Accepted, true)
op = must(t, routes.Reconcile(14).Operation)
eq(t, op.ChildPeerID, A)
eq(t, op.Reason, DemandCapacityReduction)
eq(t, op.Candidates[0].Tuple.ParentPeerID, D)
// Another reconciliation keeps this operation's original deadline.
deadline = op.DeadlineAtMs
eq(t, must(t, routes.Reconcile(15).Operation).DeadlineAtMs, deadline)
}
if outcome == "exhausted-candidates" {
prepared := beginOperation(t, routes, BeginInput{NowMs: 16,
ConnectionID: "last-leaf", Reservation: direct()})
eq(t, routes.CandidateFailed(guardFor(A, prepared.Current.Revision, "last-leaf"), 17).Accepted, true)
noOperation(t, routes.Reconcile(18).Operation)
eq(t, edgeOf(t, routes, C).PhysicalActive, false)
eq(t, edgeOf(t, routes, D).PhysicalActive, false)
eq(t, routes.physicalCopies(HOST), 2)
for now := deadline; now <= deadline+2; now++ {
noOperation(t, routes.Reconcile(now).Operation)
}
return
}
for _, child := range []string{A, B, C, D} {
eq(t, edgeOf(t, routes, child).PhysicalActive, true)
}
moved := op.ChildPeerID
commitCurrent(t, routes, 16, "leaf-to-descendant")
eq(t, edgeOf(t, routes, moved).ParentPeerID, D)
eq(t, routes.physicalCopies(HOST), 2)
eq(t, edgeOf(t, routes, C).ParentPeerID, HOST)
eq(t, edgeOf(t, routes, D).ParentPeerID, C)
for now := deadline; now <= deadline+2; now++ {
noOperation(t, routes.Reconcile(now).Operation)
}
routes.assertGraph()
})
}
}
func TestHostVideoConnectionIdentityPreservesRoomPublication(t *testing.T) {
routes := newController(2, Options{})
routes.hydrateHostPublication("logical-publication", res("publication"), "old-video")
+2 -4
View File
@@ -109,10 +109,8 @@ func (c *Controller) routeDemandReason(childPeerID string) DemandReason {
if parent, ok := c.participants.Get(edge.ParentPeerID); ok && parent.departureConfirmed {
return DemandParentDeparted
}
for _, overflowing := range c.overflowPeerChildren(edge.ParentPeerID) {
if overflowing == childPeerID {
return DemandCapacityReduction
}
if edge.PhysicalActive && len(c.overflowPeerChildren(edge.ParentPeerID)) > 0 {
return DemandCapacityReduction
}
}
return DemandEdgeUnavailable
@@ -1,6 +1,91 @@
package signal
import "testing"
import (
"sync/atomic"
"testing"
"time"
"github.com/TNTcraftHIM/Piik/internal/server/protocol"
)
func TestDisconnectedParentCannotTrapRoomCreationInPublicationPump(t *testing.T) {
h := newRouterHarness(t, routerHarnessOptions{capacity: 1, fakeTimers: true})
created := h.createRoom()
host := h.connectHost(created, nil, "", "")
viewer := h.connectViewer(created, "waiting-picture")
h.complete(host)
h.complete(viewer)
prepared := h.waitPrepared(viewer.sessionID)
h.routeReady(viewer, int64(prepared.Revision))
h.settle()
before := h.mustActiveEdge(created.RoomID, viewer.peerID)
h.locked(func() {
rm, _ := h.router.rooms.Get(created.RoomID)
rm.roomMedia, rm.mediaGeneration = true, "room_media_12345678"
rm.controller.SetVideoPublication("", false, h.router.now())
rm.controller.SetVideoPublication(testShareGeneration, false, h.router.now())
_, _ = h.store.DisconnectParticipant(created.RoomID, host.peerID, host.sessionID)
rm.controller.DisconnectSession(host.peerID, host.sessionID)
})
// Use the production HTTP mutation's mutex, shared with this same router.
server := &Server{store: h.store}
h.router.mu = &server.mu
now := h.router.now
var stop atomic.Bool
h.router.now = func() int64 {
if stop.Load() {
// Only the failing control uses this escape, so the old infinite pump
// can release its test-owned goroutine and mutex before cleanup.
panic("test cancels non-progressing pump")
}
return now()
}
pumping, pumped := make(chan struct{}), make(chan struct{})
go func() {
server.mu.Lock()
defer server.mu.Unlock()
defer close(pumped)
close(pumping)
rm, _ := h.router.rooms.Get(created.RoomID)
revision := rm.controller.Revision()
h.router.recoverPump(func() {
h.router.pumpRoom(created.RoomID, rm, rm.controller, &revision, nil, false)
})
}()
<-pumping
roomCreated := make(chan error, 1)
go func() {
_, err := server.CreateRoom(protocol.CodeEntryOpen, nil, "")
roomCreated <- err
}()
blocked := false
select {
case err := <-roomCreated:
if err != nil {
t.Error(err)
}
case <-time.After(time.Second):
blocked = true
stop.Store(true)
select {
case <-roomCreated:
case <-time.After(time.Second):
t.Fatal("test pump did not retire after cancellation")
}
}
<-pumped
server.mu.Lock()
h.router.mu, h.router.now = &h.mu, now
server.mu.Unlock()
if blocked {
t.Fatal("publication attachment to an offline parent held the room-creation mutex")
}
rm, _ := h.router.rooms.Get(created.RoomID)
after, ok := rm.controller.Snapshot().UpstreamByViewer.Get(viewer.peerID)
if !ok || after.ConnectionID != before.connectionID || !after.Usable || !after.PhysicalActive {
t.Fatal("waiting for its parent replaced the healthy room connection")
}
}
func TestStoppedShareReadyCannotCommitReplacementShare(t *testing.T) {
h := newRouterHarness(t, routerHarnessOptions{capacity: 2, fakeTimers: true})
+5 -1
View File
@@ -3,6 +3,7 @@ import { createHash } from "node:crypto";
import { openAsBlob } from "node:fs";
import { setTimeout as delay } from "node:timers/promises";
import { readReleaseArtifacts } from "./release-artifacts.mjs";
import { mirrorSourceReady } from "./release-mirror-ready.mjs";
const [directory, version, revision, option] = process.argv.slice(2);
if (option && option !== "--dry-run") {
@@ -111,6 +112,8 @@ if (option === "--dry-run") {
const body = `${source.body ?? ""}\n\nSource: https://github.com/${repository}/commit/${revision}\n\n${marker}\n`;
if (!release || release.prerelease) requireLatestSource();
if (!release) {
if (!await mirrorSourceReady(version, revision, request))
throw new Error("AtomGit Git synchronization is pending; the scheduled mirror check will resume after the matching commit and tag arrive");
const repo = await request("");
if (!repo || repo.private || !repo.default_branch) throw new Error("A public initialized AtomGit mirror is required");
release = await request("/releases", "POST", {
@@ -133,8 +136,9 @@ if (option === "--dry-run") {
// Signed locations and callback headers are credentials; never log them.
let response;
try {
// The signed APK exceeded three minutes on the cross-border upload path.
response = await fetch(upload.url, { method: "PUT", redirect: "error", headers: upload.headers,
body: await openAsBlob(file.path), signal: AbortSignal.timeout(180_000) });
body: await openAsBlob(file.path), signal: AbortSignal.timeout(600_000) });
if (!response.ok) throw new Error("HTTP " + response.status);
await response.arrayBuffer();
} catch (error) {
+1 -1
View File
@@ -30,7 +30,7 @@ for (const server of servers) {
}
function verifyImage(reference, server) {
const metadata = JSON.parse(run("docker", "image", "inspect", reference))[0];
const metadata = JSON.parse(run("docker", "image", "inspect", "--platform", `linux/${server.arch}`, reference))[0];
assert.equal(metadata.Os, "linux");
assert.equal(metadata.Architecture, server.arch);
const labels = metadata.Config.Labels;
+68
View File
@@ -0,0 +1,68 @@
import { execFileSync } from "node:child_process";
import { appendFileSync } from "node:fs";
import { pathToFileURL } from "node:url";
const repository = "TNTcraftHIM/Piik";
export async function readMirror(path) {
const response = await fetch(`https://api.atomgit.com/api/v5/repos/${repository}${path}`, {
redirect: "error", signal: AbortSignal.timeout(30_000), headers: { Accept: "application/json" },
});
if (response.status === 404) return null;
if (!response.ok) throw new Error(`AtomGit readiness ${path}: HTTP ${response.status}`);
return response.json();
}
// Git synchronization belongs to AtomGit. Release creation must never create a tag.
export async function mirrorSourceReady(version, revision, read = readMirror) {
const commit = await read(`/commits/${revision}`);
if (!commit) return false;
if (commit.sha !== revision) throw new Error("AtomGit source commit differs from the published source");
for (let page = 1; page <= 10; page++) {
const tags = await read(`/tags?per_page=100&page=${page}`);
if (!Array.isArray(tags)) throw new Error("Unexpected AtomGit tag list");
const tag = tags.find(tag => tag.name === version);
if (tag) {
if (tag.commit?.sha !== revision) throw new Error("AtomGit release tag belongs to another source revision");
return true;
}
if (tags.length < 100) return false;
}
throw new Error("AtomGit tag inventory exceeds 10 pages; source readiness cannot be determined");
}
export async function mirrorReadiness(source, read = readMirror) {
if (source.draft !== false || source.prerelease !== false || typeof source.tag_name !== "string"
|| !/^[a-f0-9]{40}$/.test(source.target_commitish)) throw new Error("A published GitHub release with a full source SHA is required");
const version = source.tag_name, revision = source.target_commitish;
const mirror = await read(`/releases/tags/${encodeURIComponent(version)}`);
if (mirror) {
if (mirror.tag_name !== version || ![true, false].includes(mirror.prerelease)
|| !mirror.body?.split(/\r?\n/).includes(`<!-- piik-source: ${revision} -->`))
throw new Error("Existing mirror release belongs to a different or unknown source revision");
const packages = source.assets?.filter(asset => asset.name?.startsWith("piik-"));
const complete = packages?.length > 0 && Array.isArray(mirror.assets) && packages.every(asset => {
const matches = mirror.assets.filter(candidate => candidate.type === "attach" && candidate.name === asset.name);
return asset.state === "uploaded" && /^sha256:[a-f0-9]{64}$/.test(asset.digest ?? "")
&& matches.length === 1 && matches[0].size === asset.size
&& matches[0].browser_download_url === `https://atomgit.com/${repository}/releases/download/${version}/${asset.name}`;
});
if (!mirror.prerelease) {
if (!complete) throw new Error("Published mirror is incomplete; it cannot be silently replaced");
return { status: "complete", version, revision };
}
}
return { status: await mirrorSourceReady(version, revision, read) ? "ready" : "deferred", version, revision };
}
if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
const source = JSON.parse(execFileSync("gh", ["api", `repos/${repository}/releases/latest`], {
encoding: "utf8", stdio: ["ignore", "pipe", "pipe"], timeout: 30_000,
}));
const result = await mirrorReadiness(source);
if (process.env.GITHUB_OUTPUT) appendFileSync(process.env.GITHUB_OUTPUT, `status=${result.status}\n`);
if (process.env.GITHUB_STEP_SUMMARY) appendFileSync(process.env.GITHUB_STEP_SUMMARY,
result.status === "deferred" ? `Mirror ${result.version} deferred until AtomGit's scheduled Git synchronization supplies the matching commit and tag. The next mirror check will resume automatically.\n`
: result.status === "complete" ? `Mirror ${result.version} is already stable with the complete published attachment inventory.\n`
: `Mirror ${result.version} is ready to resume from original CI artifacts.\n`);
console.log(JSON.stringify(result));
}
+10 -1
View File
@@ -9,6 +9,15 @@ const gh = (path) => JSON.parse(execFileSync("gh", ["api", `repos/${repository}/
}));
export function resolveMirrorSource(runId, automatic = false) {
if (!runId && automatic) {
const latest = gh("releases/latest");
if (latest.draft !== false || latest.prerelease !== false || !isReleaseVersion(latest.tag_name)
|| !/^[a-f0-9]{40}$/.test(latest.target_commitish)) throw new Error("A published stable GitHub release with a full source SHA is required");
const runs = gh(`actions/workflows/repository-hygiene.yml/runs?event=push&branch=main&status=completed&head_sha=${latest.target_commitish}&per_page=100`);
const source = runs.workflow_runs?.find(run => run.head_sha === latest.target_commitish);
if (!source) throw new Error("The published release's original completed CI run is unavailable; do not rebuild its packages");
return resolveMirrorSource(String(source.id), true);
}
if (!/^[1-9]\d*$/.test(runId) || !Number.isSafeInteger(Number(runId))) {
throw new Error("Provide the original CI run's numeric ID");
}
@@ -34,7 +43,7 @@ export function resolveMirrorSource(runId, automatic = false) {
}
if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
const source = resolveMirrorSource(process.argv[2], process.env.GITHUB_EVENT_NAME === "workflow_run");
const source = resolveMirrorSource(process.argv[2], ["workflow_run", "schedule"].includes(process.env.GITHUB_EVENT_NAME) || !process.argv[2]);
const output = { mirror: source !== null, ...source };
if (process.env.GITHUB_OUTPUT) {
appendFileSync(process.env.GITHUB_OUTPUT,
@@ -69,12 +69,12 @@ export function ResolutionControl({ value, limits, disabled, onChange }: {
const controls = useRef<HTMLDivElement>(null);
const [invalid, setInvalid] = useState(false);
const errorId = useId();
useEffect(() => setInvalid(false), [value.width, value.height]);
const axes = ["width", "height"] as const;
const reset = (container: HTMLElement) => {
setInvalid(false);
for (const axis of axes) container.querySelector<HTMLInputElement>(`input[name="${axis}"]`)!.value = String(value[axis]);
};
useEffect(() => { reset(controls.current!); }, [value.width, value.height]);
const apply = (container: HTMLElement) => {
const width = container.querySelector<HTMLInputElement>('input[name="width"]')!;
const height = container.querySelector<HTMLInputElement>('input[name="height"]')!;
@@ -108,7 +108,7 @@ export function ResolutionControl({ value, limits, disabled, onChange }: {
width: String(limits.maxVideoResolution.width), height: String(limits.maxVideoResolution.height),
pixels: limits.maxVideoPixels.toLocaleString("en-US"),
})}>
<span className="lr-input lr-video-size" key={`${value.width}x${value.height}`}
<span className="lr-input lr-video-size"
role="group" aria-label={t("host.advanced.resolution")}>
{axes.map((axis, index) => <Fragment key={axis}>
{index === 1 ? <span aria-hidden="true">×</span> : null}
+1
View File
@@ -3,6 +3,7 @@
.lr-person-eyes { transform-origin: 24px 14.1px; }
/* Keep the same SVG parts mounted so a second toggle reverses the gesture. */
.lr-person-headset, .lr-person-collaboration { opacity: 0; }
.lr-person-headset { color: var(--ink); }
.lr-person-status[data-voice] .lr-person-headset,
.lr-person-status[data-collaboration] .lr-person-collaboration { opacity: 1; }
.lr-person-collaboration { transform: translateY(2px) scale(.94); transform-origin: 24px 40px; }
+14 -4
View File
@@ -36,7 +36,7 @@ async function publish(options: Scenario = {}) {
const manifests = new Map<string, object>();
if (options.existing) manifests.set(tag, index);
if (options.partial) manifests.set(`${tag}-arm64`, {});
const images = new Map(servers.map(server => [`${image}-${server.arch}`, server.arch]));
const images = new Map(linuxServers.map(server => [`${image}-${server.arch}`, new Set([server.arch])]));
command.mockReset().mockImplementation((program: string, args: string[]) => {
if (program === "gh") {
if (args[1].endsWith("/commits/" + version)) {
@@ -53,9 +53,15 @@ async function publish(options: Scenario = {}) {
digest: `sha256:${options.badArchive && server.arch === "arm64" ? "c".repeat(64) : server.sha256}` })) });
}
if (args[0] === "image" && args[1] === "inspect") {
const arch = images.get(args[2]);
const reference = args.at(-1)!;
const stored = images.get(reference);
// A multi-platform store retains both variants. Inspect defaults to the
// host architecture, independently of the last platform pulled.
const requested = args.includes("--platform") ? args[args.indexOf("--platform") + 1].slice("linux/".length) : undefined;
const arch = requested ?? (stored?.has("amd64") ? "amd64" : [...stored ?? []][0]);
expect(arch).toBeDefined();
const remote = args[2].startsWith("ghcr.io/");
expect(stored?.has(arch!)).toBe(true);
const remote = reference.startsWith("ghcr.io/");
return JSON.stringify([{ Os: "linux", Architecture: options.wrongPlatform && arch === "arm64" ? "amd64" : arch, Config: { Labels: {
"org.opencontainers.image.version": version,
"org.opencontainers.image.revision": (options.wrongImage && arch === "arm64") || (options.remoteMismatch && remote)
@@ -78,7 +84,11 @@ async function publish(options: Scenario = {}) {
}
return JSON.stringify(manifests.get(reference));
}
if (args[0] === "pull") images.set(args[3], args[2].slice("linux/".length));
if (args[0] === "pull") {
const variants = images.get(args[3]) ?? new Set<string>();
variants.add(args[2].slice("linux/".length));
images.set(args[3], variants);
}
if (args[0] === "tag") images.set(args[2], images.get(args[1])!);
if (args[0] === "push") manifests.set(args[1], {});
if (args[0] === "buildx" && args[2] === "create") manifests.set(args[4], index);
+9 -1
View File
@@ -53,7 +53,7 @@ describe("AtomGit mirror publication", () => {
});
async function mirror(options: { existing?: "pending" | "published" | "unknown"; corrupt?: boolean;
wrongSource?: boolean; wrongDigest?: boolean; missing?: boolean; uploadFailure?: boolean | number;
stale?: boolean; supersededDuringUpload?: boolean;
stale?: boolean; supersededDuringUpload?: boolean; mirrorSourceMissing?: boolean;
downloadFault?: { remaining: number; name: "TimeoutError" | "TypeError" };
fault?: { method: string; remaining: number; status: number | "timeout" | "body-timeout" } } = {}) {
const interrupted = (bytes: Uint8Array, error: Error) => {
@@ -128,6 +128,8 @@ describe("AtomGit mirror publication", () => {
? Response.json({ id: 42, tag_name: version, body: options.existing === "unknown" ? "unknown" : marker,
prerelease: pending, assets: [...present] }) : new Response(null, { status: 404 });
if (path === "") return Response.json({ private: false, default_branch: "master" });
if (path === `/commits/${revision}`) return options.mirrorSourceMissing ? new Response(null, { status: 404 }) : Response.json({ sha: revision });
if (path === "/tags?per_page=100&page=1") return Response.json([{ name: version, commit: { sha: revision } }]);
if (path === "/releases" && method === "POST") {
const body = JSON.parse(String(init?.body));
expect(body.release_status).toBe("pre");
@@ -165,6 +167,12 @@ describe("AtomGit mirror publication", () => {
return { mutations, failure };
}
it("waits for AtomGit Git synchronization without creating a release or tag", async () => {
const result = await mirror({ mirrorSourceMissing: true });
expect(result.failure).toContain("Git synchronization is pending");
expect(result.mutations).toEqual([]);
});
it("copies the published bytes, verifies anonymous downloads and marks stable last", async () => {
const result = await mirror();
expect(result.failure).toBeUndefined();
+54
View File
@@ -0,0 +1,54 @@
import { expect, test, vi } from "vitest";
import { mirrorReadiness, mirrorSourceReady, readMirror } from "../scripts/release-mirror-ready.mjs";
const revision = "a".repeat(40), version = "v2.6.1";
const asset = { name: "piik-app-fixture.zip", state: "uploaded", size: 1024, digest: `sha256:${"b".repeat(64)}` };
const source = { tag_name: version, target_commitish: revision, draft: false, prerelease: false, assets: [asset] };
const mirror = { tag_name: version, prerelease: false, body: `<!-- piik-source: ${revision} -->`, assets: [{
type: "attach", name: asset.name, size: asset.size, browser_download_url: `https://atomgit.com/TNTcraftHIM/Piik/releases/download/${version}/${asset.name}`,
}, ...["zip", "tar.gz", "tar.bz2", "tar"].map(extension => ({ type: "source", name: `${version}.${extension}` }))] };
test("a completed stable mirror needs only its metadata and no source search or package download", async () => {
const read = vi.fn(async () => mirror);
expect(await mirrorReadiness(source, read)).toEqual({ status: "complete", version, revision });
expect(read.mock.calls).toEqual([[`/releases/tags/${version}`]]);
});
test.each(["commit", "tag"])("missing synced %s defers without a Git mutation", async missing => {
const read = vi.fn(async (path: string) => path.startsWith("/releases/") ? null
: path.startsWith("/commits/") ? missing === "commit" ? null : { sha: revision } : []);
expect(await mirrorReadiness(source, read)).toEqual({ status: "deferred", version, revision });
});
test("a pending release resumes only after its exact tag and source exist", async () => {
const read = vi.fn(async (path: string) => path.startsWith("/releases/") ? { ...mirror, prerelease: true, assets: [] }
: path.startsWith("/commits/") ? { sha: revision } : [{ name: version, commit: { sha: revision } }]);
expect(await mirrorReadiness(source, read)).toEqual({ status: "ready", version, revision });
expect(read.mock.calls.every(([path]) => path.startsWith("/releases/") || path.startsWith("/commits/") || path.startsWith("/tags?"))).toBe(true);
});
test("a missing attachment in a published release and a conflicting tag fail rather than silently repairing identity", async () => {
await expect(mirrorReadiness(source, async () => ({ ...mirror, assets: [] }))).rejects.toThrow("incomplete");
await expect(mirrorSourceReady(version, revision, async (path: string) => path.startsWith("/commits/")
? { sha: revision } : [{ name: version, commit: { sha: "c".repeat(40) } }])).rejects.toThrow("another source");
});
test("a provider source archive cannot stand in for a published package", async () => {
await expect(mirrorReadiness(source, async () => ({ ...mirror,
assets: mirror.assets.map(asset => ({ ...asset, type: "source" })),
}))).rejects.toThrow("incomplete");
});
test("a truncated tag inventory fails after ten pages rather than claiming the source is absent", async () => {
const read = vi.fn(async (path: string) => path.startsWith("/commits/") ? { sha: revision }
: Array.from({ length: 100 }, (_, index) => ({ name: `other-${index}`, commit: { sha: revision } })));
await expect(mirrorSourceReady(version, revision, read)).rejects.toThrow("exceeds 10 pages");
expect(read).toHaveBeenCalledTimes(11);
expect(read.mock.calls.at(-1)).toEqual(["/tags?per_page=100&page=10"]);
});
test("readiness treats an unavailable API as failure, not pending synchronization", async () => {
vi.stubGlobal("fetch", vi.fn(async () => new Response(null, { status: 503 })));
try { await expect(readMirror("/commits/" + revision)).rejects.toThrow("HTTP 503"); }
finally { vi.unstubAllGlobals(); }
});
+7
View File
@@ -25,6 +25,13 @@ function api(source = run, latest = release) {
beforeEach(() => { command.mockReset(); api(); });
describe("mirror source authority", () => {
it("scheduled recovery finds the original completed main CI by published source", () => {
const existing = command.getMockImplementation()!;
command.mockImplementation((program: string, args: string[]) => args[1].includes("actions/workflows/")
? JSON.stringify({ workflow_runs: [run] }) : existing(program, args));
expect(resolveMirrorSource("", true)).toEqual({ run_id: "12345", version: release.tag_name, revision });
expect(command.mock.calls.some(([, args]) => args[1].includes(`head_sha=${revision}`))).toBe(true);
});
it("binds automatic and manual retries to the published source run", () => {
const expected = { run_id: "12345", version: release.tag_name, revision };
expect(resolveMirrorSource("12345", true)).toEqual(expected);