Compare commits

...
6 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.
  • fix(app): stabilize authorization and compact room controls
    ## Problem and outcome / 问题与结果
    
    App authorization could stay busy after a stalled save, a pending microphone request could survive a capture-source handoff, and compact room controls could lose focus, position or readable names. This maintenance phase corrects those owners and makes connection help easier to find.
    
    ## Verification / 验证
    
    Validation: the exact candidate tree passed all 1,943 Web tests and documentation checks. Its unchanged product source has passed TypeScript and a production Web build. Controlled UI checks cover delayed microphone permission, stalled approval responses, keyboard viewport changes, rapid floating-panel hide/show and narrow nickname layouts. Published 2.x wire, native control and storage contracts are unchanged.
    
    ## Impact / 影响
    
    Compatible 2.x maintenance release. Existing App, site and persisted room contracts are retained. Matching packages, download mirrors and both managed sites are verified through the normal release workflow.
    
    ## 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 improves App authorization, capture-source switching and controls on smaller screens.
    
    - Fix commentary controls remaining busy after switching from Browser capture to the App.
    - Let App site approval recover from a stalled save, keeping access already granted.
    - Preserve numeric-input focus when the mobile keyboard resizes the page, and provide increase/decrease buttons. Keep interaction windows at their remembered position after rapid hide/show actions.
    - Give nicknames readable space on smaller screens, while retaining edit controls and accessible labels. Keep launcher diagnostics inside the shared Help menu.
    - Make room-connection help easier to find, and clarify Safari screen-sharing and sound support.
    - Complete package mirroring after a later CI publication step fails, and verify managed-service deployments against the intended source revision.
    
    This maintenance update preserves the established 2.x room, invitation, media,
    App-control and storage contracts. Refresh a site's open pages after it is
    updated. App-local users need the updated App bundle to receive its included
    Web fixes. Existing compatible 2.x App/site workflows remain supported.
    
    ### 中文
    
    本次维护更新改善 App 授权、切换分享源和小屏操作。
    
    - 修复浏览器切换为 App 采集后,分享麦克风控制一直处于忙碌状态的问题。
    - App 站点授权不再因保存卡住而一直转圈;可以重试,已批准的授权也会保留。
    - 手机键盘改变页面尺寸时保留数字输入焦点,并提供增减按钮;互动窗口快速隐藏再打开后保留记忆位置。
    - 小屏上为昵称保留可读空间,同时保留编辑入口与无障碍名称;启动页诊断统一收进帮助菜单。
    - 更容易找到房间连接问题的排查入口,并说明 Safari 屏幕分享与声音的支持情况。
    - 发布流程后续步骤失败时,仍可补全已经发布的程序包镜像;部署核验明确比对预期源码版本。
    
    本维护更新保留既有 2.x 房间、邀请、媒体、App 控制与存储契约。
    站点更新后请刷新已打开的网页;App 本地使用者需更新程序包,才能使用其中的新网页修复。
    已有兼容的 2.x App/站点使用方式继续支持。
  • fix(ops): verify the expected revision on managed services (#528)
    The Demo and managed private service were still serving older releases after v2.6.0 packages and the website had been published. A healthy response alone did not detect the missed service cutover.
    
    Add an optional `server-check --revision FULL_SOURCE_SHA` to verify the actual running package against the release descriptor, and make both managed-service postflight checks explicit in the deployment runbook. Existing health-only checks remain available. This changes operator tooling and documentation only; it does not publish another product version.
    
    Validation: both managed services pass with the v2.6.0 source revision; a check against the previous Demo revision exits with failure. JavaScript syntax, diff, documentation and repository hygiene checks pass. Both sites have separately been deployed using the original v2.6.0 artifacts.
  • fix(ci): inspect raw OCI indexes when publishing containers (#527)
    `docker manifest inspect` reconstructs an image index and drops descriptor annotations. The v2.6.0 registry index correctly marks its BuildKit attestation, but the transformed CLI output loses that marker and the publisher counts `unknown/unknown` as another runnable platform.
    
    Read the original index with `docker buildx imagetools inspect --raw`. Keep the explicit attestation filter, exact runnable-platform set and image/source/archive checks. Treat only an exact missing-reference error as absence; permission, network and missing-blob errors still stop publication.
    
    The regression now distinguishes the old CLI's annotation loss from the raw index response. Container/package publisher and mirror-source checks pass (65 tests), including new/retained attestation indexes, unmarked unknown platforms and lookup failures.
    
    The actual v2.6.0 index and both image configs were read anonymously. Their version, source SHA and Server archive digests match the published release. The original index bytes were used to finish the `latest` alias; the version tag, images and release attachments were not rebuilt or replaced. This is a publishing-tool correction and does not create another product version.
    
    Primary references: [Docker CLI descriptor reconstruction](https://github.com/docker/cli/blob/master/cli/command/manifest/push.go#L132), [Buildx raw inspection](https://docs.docker.com/reference/cli/docker/buildx/imagetools/inspect/).
58 changed files with 1024 additions and 135 deletions

No files matched your search

+21 -7
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,10 +27,9 @@ 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' &&
github.event.workflow_run.conclusion == 'success'))
github.event.workflow_run.head_branch == 'main'))
runs-on: ubuntu-latest
timeout-minutes: 30
steps:
@@ -36,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
@@ -78,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 }}
+20
View File
@@ -224,6 +224,26 @@ schema validation fails closed before accepting signaling or media admission.
## Postflight
Package publication, the website, and running Piik services are separate delivery
targets. CI publishes packages and the website; it does not update the managed
Demo or private service. Complete their authorized deployment before reporting
the release as deployed, and verify each service against the release descriptor:
```sh
node --env-file=.env.maintenance.demo.local scripts/release-maintenance.mjs server-check --revision FULL_SOURCE_SHA
node --env-file=.env.maintenance.private.local scripts/release-maintenance.mjs server-check --revision FULL_SOURCE_SHA
```
The website's latest-version card reads GitHub metadata and cannot establish
which release either service is running.
Download mirrors have a separate completion check: the AtomGit stable/latest
release must match the published version and source, and every package must pass
the mirror publisher's anonymous download and checksum verification. A green
workflow that skipped its upload step is not mirror completion. Keep a failed
mirror in the active TODO ledger until recovery and postflight succeed; source
synchronization alone does not publish download attachments.
Verify only the surfaces relevant to the release:
- local and public `/healthz` return `{"status":"ok"}`;
+2 -2
View File
@@ -28,8 +28,8 @@ Choose a guide to start sharing, use room tools or solve a problem.
## Get help
- **App, sharing or sound problems:** start with the [symptom index](./troubleshooting.md#common-problems).
- **Campus networks, media connections or virtual LANs:** use [network checks](./network.md) to choose a connection option.
- **Cannot join, share or hear a friend:** [find the checks for your problem](./troubleshooting.md#common-problems).
- **The page opens, but picture or voice still will not connect:** after the basic checks, use [network checks](./network.md) to compare browsers, networks or a virtual LAN.
Still stuck? [Report a problem](https://github.com/TNTcraftHIM/Piik/issues/new/choose)
with your version, system, browser and reproduction steps. Follow the
+2 -2
View File
@@ -28,8 +28,8 @@
## 遇到问题
- **App、分享或声音异常:** 从[问题排查的症状索引](./troubleshooting.zh-CN.md#常见问题)开始。
- **校园网、画面连不上或虚拟局域网:** 查看[进阶网络排查](./network.zh-CN.md),按现象选择连接方案。
- **进不了房间、无法分享或听不到朋友:** 先看[对应的排查步骤](./troubleshooting.zh-CN.md#常见问题)。
- **网页能打开,基本检查后画面或语音仍连不上:** 再看[进阶网络排查](./network.zh-CN.md),对照浏览器、网络或虚拟局域网。
仍然没解决?可以[反馈问题](https://github.com/TNTcraftHIM/Piik/issues/new/choose),
附上版本、系统、浏览器和复现步骤。需要收集报告时,按[反馈说明](./troubleshooting.zh-CN.md#反馈问题)导出。
+4
View File
@@ -40,6 +40,10 @@ you do not need to create a room in your App to watch them.
second device or send it to a friend.
4. Select **Stop sharing** when finished.
On iPhone/iPad, screen sharing requires **Safari on iOS/iPadOS 27 or later**.
See [iPhone and iPad screen sharing](./sharing.md#iphone-and-ipad-screen-sharing)
for sound support and the separate requirements for watching and cameras.
The online version is provided by the project. Media travels only between participants (P2P);
restrictive networks may load the page but block video.
+3
View File
@@ -36,6 +36,9 @@ Piik 支持一位房主分享屏幕,最多 20 位受邀观众观看。先选
3. 确认预览后,点击 **复制邀请链接**,用另一台设备打开,或发送给朋友。
4. 分享结束后,点击 **停止分享**。
iPhone/iPad 屏幕分享需使用 **iOS/iPadOS 27 及以上的 Safari**。
声音支持及观看、摄像头的区别,见 [iPhone 与 iPad 屏幕分享](./sharing.zh-CN.md#iphone-与-ipad-屏幕分享)。
在线版由项目提供,画面仅通过设备间直连(P2P)传输。
在受限网络下,可能出现页面能打开、画面无法连接的情况。
+13 -12
View File
@@ -2,22 +2,21 @@
English · [简体中文](./network.zh-CN.md) · [Troubleshooting](./troubleshooting.md)
Use this page when **the page opens, but picture or voice will not connect**.
Choose the relevant check:
Start with the [basic connection checks](./troubleshooting.md#common-problems).
If you still cannot connect, choose what matches:
- **Campus/work network, or the same invite works on a hotspot:** [connection options](#campus-networks-and-strict-nat).
- **The same invite works in another browser:** [browser restrictions](#browser-webrtc-restrictions).
- **The same invite works on a hotspot:** [connection options](#campus-networks-and-strict-nat).
- **Friends in another location cannot reach your local invitation:** [connect through a virtual LAN](#optional-a-virtual-lan).
- **Logs mention STUN, or you manage the router:** [discovery and router checks](#stun-ipv6-and-router-checks).
- **Using Tailscale, ZeroTier or UU:** [virtual LAN steps](#optional-a-virtual-lan).
Web pages and chat use a separate connection from picture and sound.
For media failures, check WebRTC UDP and the route options below.
If a [public-invitation page will not open](./troubleshooting.md#public-invitation-fails-or-shows-1033)
or [video plays but blurs or stutters](./troubleshooting.md#picture-blurs-stutters-or-stops), follow that symptom instead.
Web pages and chat use a separate connection from picture and sound:
![The Host and friend access the site for web and chat; picture and sound use a separate direct or forwarded media connection.](../assets/guide/network-paths.en.svg)
If the [invitation page will not open](./troubleshooting.md#public-invitation-fails-or-shows-1033),
or [video already plays but blurs or stutters](./troubleshooting.md#picture-blurs-stutters-or-stops), start with that symptom instead.
## Campus networks and strict NAT
**Open the same invitation on a phone hotspot first.** If it works there but not
@@ -26,7 +25,7 @@ on the original network, investigate that network's shared gateway or firewall.
For regular use, choose an option that fits your group:
- **You have a Piik site:** ask its operator to [enable server media forwarding (SFU)](../operations/self-hosting.md#optional-media-fallback). The Host turns off **Privacy mode** so forwarding can be tried if direct connections fail. For App capture, [approve the new site](./getting-started.md#use-app-with-an-existing-site), then send its invitation.
- **Everyone can install a networking tool:** use the [virtual LAN steps](#optional-a-virtual-lan) below with the App's **Local room**.
- **No usable forwarding site, and direct media still will not connect:** a [virtual LAN](#optional-a-virtual-lan) offers another path. Everyone joins the same virtual network, then uses the App's **Local room**.
- **The required connections are blocked:** use an available network or ask its administrator to review access.
> **Media requires UDP.** `demo.piik.tv` and App **Public invite** use P2P-only media.
@@ -102,8 +101,10 @@ and [double NAT](https://www.tp-link.com/us/support/faq/3113/).
## Optional: a virtual LAN
A virtual LAN connects devices in different places, so you can share through
Piik App's **Local room**. The tool must provide reachable virtual IPv4 addresses
If friends elsewhere cannot reach your local invitation, or direct media still
will not connect after the basic checks, try a virtual LAN. It connects your
devices so you can use Piik App's **Local room** instead of the public-invite path.
The tool must provide reachable virtual IPv4 addresses
and carry both web traffic and WebRTC UDP; acceleration limited to one game does
not suffice. Choose a tool available to everyone in your group:
+10 -8
View File
@@ -2,19 +2,20 @@
[English](./network.md) · 简体中文 · [问题排查](./troubleshooting.zh-CN.md)
本页用于排查 **网页能打开,但画面或语音连接不上**。按你的情况选择:
先做[连接问题的基本检查](./troubleshooting.zh-CN.md#常见问题)。
仍然连不上时,再按现象选择:
- **校园网、公司网络,或换成热点就能看:** [选择连接方案](#校园网或严格-nat)。
- **同一邀请在别的浏览器里正常:** [检查浏览器限制](#浏览器限制了-webrtc)。
- **换成热点就能看:** [选择连接方案](#校园网或严格-nat)。
- **异地朋友打不开你的本地邀请:** [通过虚拟局域网连接](#可选虚拟局域网)。
- **日志提到 STUN,或准备检查自家路由器:** [地址发现与路由器](#stunipv6-与路由器检查)。
- **准备使用 UU、Tailscale 或 ZeroTier:** [虚拟局域网使用步骤](#可选虚拟局域网)。
网页与聊天、画面与声音使用不同的连接。媒体连接失败时,检查 WebRTC UDP 和下方的连接方案。
如果是[公网邀请网页打不开](./troubleshooting.zh-CN.md#公网邀请创建失败或出现-1033),或[有画面但模糊、卡顿](./troubleshooting.zh-CN.md#画面模糊卡顿或中断),先按对应症状排查。
网页与聊天、画面与声音使用不同的连接:
![房主和朋友通过站点访问网页与聊天;画面和声音使用独立的直连或转发连接。](../assets/guide/network-paths.zh-CN.svg)
如果是[邀请网页打不开](./troubleshooting.zh-CN.md#公网邀请创建失败或出现-1033),或[画面已经出现但模糊、卡顿](./troubleshooting.zh-CN.md#画面模糊卡顿或中断),先按对应症状排查。
## 校园网或严格 NAT
**先用手机热点打开同一邀请。** 热点能看、原网络不能看时,原网络的共享出口或防火墙限制更值得检查。
@@ -22,7 +23,7 @@
需要长期使用时,可以选择以下方案:
- **有可用的 Piik 站点:** 请管理员[启用服务器媒体转发(SFU)](../operations/self-hosting.zh-CN.md#可选启用媒体兜底),房主关闭 **隐私模式**,直连失败时即可尝试转发。使用 App 采集时,[授权新站点](./getting-started.zh-CN.md#通过已有站点使用-app),再发送该站点的邀请。
- **朋友们可以安装组网工具:** 按下方[虚拟局域网步骤](#可选虚拟局域网),通过 App 的 **本地房间** 分享。
- **没有可用的转发站点,直连仍然失败:** 可尝试[虚拟局域网](#可选虚拟局域网)。朋友们加入同一个虚拟网络,再通过 App 的 **本地房间** 分享。
- **所需的连接被网络阻断:** 换用可用网络,或请网络管理员检查放行。
> **媒体需要 UDP。** `demo.piik.tv` 和 App 的 **公网邀请** 使用纯 P2P。
@@ -89,7 +90,8 @@ STUN 服务会接收到参与者的公网 IP,请选择信任的服务。
## 可选:虚拟局域网
虚拟局域网让异地设备像在同一网络中一样互访,再通过 Piik App 的 **本地房间** 分享。
异地朋友打不开本地邀请,或基本检查后画面、语音仍然连不上时,可以尝试虚拟局域网。
它让设备像在同一网络中一样互访,改用 Piik App 的 **本地房间** 分享。
工具必须提供可互访的虚拟 IPv4 地址,同时支持网页访问和 WebRTC UDP;只加速某个游戏的功能不适用。
选择朋友们都能使用的工具即可:
+12
View File
@@ -41,6 +41,18 @@ sharing. Viewers hear it through the picture's sound without joining room voice.
Room voice remains independent. If you enable both microphones, listeners may
hear you twice; Piik warns you and leaves the choice to you.
## iPhone and iPad screen sharing
Use **Safari on iOS/iPadOS 27 or later** and select **Browser** to share your screen.
Watching a friend and camera sharing use the browser's existing capabilities
and do not require this screen-sharing version.
Safari screen sharing does **not** capture system audio. To speak with the picture,
explicitly enable [Include my microphone](#include-your-microphone).
MDN's [verified Safari 27 support](https://github.com/mdn/browser-compat-data/pull/30732)
and [screen/audio compatibility data](https://github.com/mdn/browser-compat-data/blob/main/api/MediaDevices.json)
distinguish screen capture from audio capture.
## Cameras and virtual audio inputs
Picture sound and conversation use separate controls. Muting one does not mute the other.
+9
View File
@@ -34,6 +34,15 @@
每次开始新的分享时默认关闭,停止分享也会停止这路麦克风。观众通过画面声音收听,无须加入房间语音。
房间语音独立运行。如果同时开启两路麦克风,听众可能听到两次你的声音;Piik 会提示,由你决定保留哪一路。
## iPhone 与 iPad 屏幕分享
请使用 **iOS/iPadOS 27 及以上的 Safari**,选择 **浏览器** 分享屏幕。
观看朋友的画面和分享摄像头使用浏览器已有能力,不受此屏幕分享版本门槛限制。
Safari 屏幕分享**不采集系统声音**。需要随画面讲话时,可主动开启[分享麦克风](#分享麦克风)。
依据 MDN 的 [Safari 27 实测记录](https://github.com/mdn/browser-compat-data/pull/30732)
及[屏幕/音频兼容数据](https://github.com/mdn/browser-compat-data/blob/main/api/MediaDevices.json),两者支持情况不同。
## 摄像头与虚拟音频输入
![来源声音与分享麦克风随画面传输,使用播放音量;房间语音使用独立的收听音量。](../assets/guide/audio-paths.zh-CN.svg)
+8 -1
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
@@ -516,7 +522,8 @@ Read discovery logs or check a router you manage. [View steps](./network.md#stun
### Optional: a virtual LAN
Use Local room over Tailscale, ZeroTier or UU. [View steps](./network.md#optional-a-virtual-lan).
Friends elsewhere cannot reach a local invitation, or direct media still will not
connect? A virtual LAN provides another connection option. [View steps](./network.md#optional-a-virtual-lan).
## Reporting a problem
+6 -1
View File
@@ -359,6 +359,10 @@ Windows 需要用户授权;其他采集要求显示边框时,边框仍会保
2. 房主应选择支持分享声音的来源,并在选源器中打开声音;可用声音取决于来源和平台。
3. 摄像头画面与麦克风输入分别选择。内置麦克风或 OBS 音频的用法,见[摄像头与音频输入](./sharing.zh-CN.md#摄像头与虚拟音频输入)。
使用虚拟混音器或多个输出设备时,先检查应用把声音送到了哪里。未启用应用声音排除时,
Windows App 的屏幕采集使用默认播放设备;可以改选该应用的窗口来采集程序声音,
或把应用声音送到默认播放设备后重新分享屏幕。
### 听不到说话声
如果房主使用 **分享麦克风**,先检查画面的[来源声音](#有画面但没有来源声音),
@@ -425,7 +429,8 @@ Piik 的麦克风静音不会关闭这条独立来源。
### 可选:虚拟局域网
通过 UU 等组网工具使用本地房间。 [查看步骤](./network.zh-CN.md#可选虚拟局域网)。
异地朋友打不开本地邀请,或直连始终失败时,可尝试通过虚拟局域网连接。
[查看步骤](./network.zh-CN.md#可选虚拟局域网)。
## 反馈问题
+28 -3
View File
@@ -94,22 +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 successful main-push CI run, the workflow downloads that 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`.
It skips runs that did not publish the current GitHub release. 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
+2
View File
@@ -104,6 +104,8 @@ node --env-file=.env.maintenance.local scripts/release-maintenance.mjs server-ch
root/index asset references. `website-purge` clears those entry points from
Cloudflare; visitors' Browser caches remain separate. `server-check` is a read-only
SSH check of the Linux `piik` service, running package and public health.
After deployment, pass `--revision FULL_SOURCE_SHA` from the release descriptor;
an older healthy service then fails the check.
Keep separate ignored env files or SSH aliases for different Server targets;
keep private connection details out of scripts. For package upload, cutover
and recovery, follow [Server deployment](../deployment.md).
+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;
+34
View File
@@ -66,6 +66,35 @@ Keep existing controls in their established positions as a room becomes active.
Represent missing room identity with a passive placeholder in its own slot;
do not move unrelated controls into that space to fill an empty state.
### Space Priority
Assign space by meaning before choosing a breakpoint. The containing row or
toolbar owns its layout; the shared control declares whether its caption may
collapse. Primary styling, a quiet appearance or a particular icon does not
determine that priority.
| Content or action | Behavior when space is limited |
| --- | --- |
| A name, selected device or other object being acted on | Give the value space before its supporting action's caption. After that, keep the group together where possible; long names may use the full available line and then ellipsis with their existing full-value hint. |
| Exact short values, units, entry fields and validation | Keep the value and unit together; preserve usable editing width. Wrap the field group or explanation instead of clipping the value or shrinking its type. |
| Contextual actions with a familiar icon, such as Edit or Copy | Explicitly allow the caption to collapse first. Retain the same icon, accessible name, hint and normal click target. |
| Primary, destructive or unfamiliar choices | Keep enough visible identity to distinguish the action and its scope; retain wording when an icon would be ambiguous. Wrap complete actions or their group. |
| Secondary utilities and detail settings | Reuse the surface's existing More/settings disclosure when needed. Keep frequent playback, mute and stop/release controls directly reachable. |
Use this order: remove surplus spacing, collapse eligible supporting captions,
reflow coherent groups, then shorten long descriptive values. Do not reduce all
children equally or use blanket `nowrap` to force a row to fit. For example,
the nickname gets space before the word **Edit**; the pencil remains beside it
until the whole identity group needs its own line.
`Btn` owns optional caption collapse and button geometry. Layout owners select
the applicable container state; they must not copy per-page glyph sizes or hide
all captions indiscriminately. Header overflow remains its existing single
disclosure and focus owner. The website and room UI follow these same priorities
while keeping their distinct layouts. Check real short/long values, translated
labels, active/editing states and text zoom; fitting inside the viewport alone
does not prove the important content stayed readable.
### Control Selection
Choose by the user's task, then reuse its interaction and visual primitive.
@@ -817,6 +846,11 @@ stationary and manually scrollable instead of discarding the hidden words.
## Interaction References
[Fluent toolbars](https://fluent2.microsoft.design/components/web/react/core/toolbar/usage)
and [Atlassian navigation layout](https://atlassian.design/components/navigation-system/layout/code)
distinguish directly available actions from overflow. Piik applies those priorities
through its existing controls and layout owners, not a second toolbar framework.
[Radix colour roles](https://www.radix-ui.com/colors/docs/palette-composition/understanding-the-scale)
separate surfaces, interaction states, borders and text instead of tinting every
layer with the accent. Native [text selection](https://developer.mozilla.org/en-US/docs/Web/CSS/user-select)
+11 -1
View File
@@ -1,12 +1,22 @@
# Current TODO Ledger
Last reviewed: 2026-11-04
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
those pixels with the existing colour controls; increased bitrate did not
resolve the reported tint.
- [ ] **Browser sharing falls to low source FPS during motion.** Capture original
track, isolated capture-input and sender counters during the same low-FPS
episode on Windows Chrome with mixed direct/SFU delivery. The observed sender
+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) {
+4 -3
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;
@@ -40,10 +40,11 @@ function verifyImage(reference, server) {
}
const tag = `${destination}:${version}`;
function manifest(reference) {
try { return JSON.parse(run("docker", "manifest", "inspect", reference)); }
// manifest inspect reconstructs the list and drops descriptor annotations.
try { return JSON.parse(run("docker", "buildx", "imagetools", "inspect", "--raw", reference)); }
catch (error) {
// Authentication/network failures are not evidence that a tag is absent.
if (!/manifest unknown|no such manifest/i.test(String(error.stderr ?? ""))) throw error;
if (String(error.stderr ?? "").trim().replace(/^ERROR: /, "") !== `${reference}: not found`) throw error;
return null;
}
}
+13 -4
View File
@@ -2,14 +2,22 @@
import assert from "node:assert/strict";
import { execFileSync } from "node:child_process";
import { parseArgs } from "node:util";
const command = process.argv[2] ?? "website-check";
const { values, positionals } = parseArgs({ options: {
help: { type: "boolean" }, revision: { type: "string" },
}, allowPositionals: true });
const command = positionals[0] ?? "website-check";
const commands = ["website-check", "website-purge", "server-check"];
if (command === "--help") {
console.log("Usage: node --env-file=.env.maintenance.local scripts/release-maintenance.mjs <command>\nCommands: " + commands.join(", "));
if (values.help) {
console.log("Usage: node --env-file=.env.maintenance.local scripts/release-maintenance.mjs <command> [--revision <full-source-SHA>]\nCommands: " + commands.join(", ") + "\n--revision verifies the expected server deployment.");
process.exit(0);
}
assert.ok(commands.includes(command) && process.argv.length <= 3, "Unknown maintenance command; use --help.");
assert.ok(commands.includes(command) && positionals.length <= 1, "Unknown maintenance command; use --help.");
if (values.revision !== undefined) {
assert.equal(command, "server-check", "--revision applies only to server-check.");
assert.match(values.revision, /^[a-f0-9]{40}$/, "Use the release descriptor's full source revision.");
}
const required = name => {
const value = process.env[name]?.trim();
assert.ok(value, `Set ${name} in the local maintenance env file.`);
@@ -94,6 +102,7 @@ print(json.dumps({
assert.equal((await response.json()).status, "ok");
assert.equal(remote.service, "active");
assert.equal(remote.runningPackage, true, "The running binary differs from the current release.");
if (values.revision) assert.equal(remote.revision, values.revision, "The service is not running the expected release.");
return { ...remote, origin: origin.origin, health: true, passed: true };
}
+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));
}
+13 -5
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");
}
@@ -16,12 +25,11 @@ export function resolveMirrorSource(runId, automatic = false) {
if (run.id !== Number(runId) || run.repository?.full_name !== repository ||
run.head_repository?.full_name !== repository || run.event !== "push" ||
run.head_branch !== "main" || run.path !== ".github/workflows/repository-hygiene.yml" ||
run.status !== "completed" || !/^[a-f0-9]{40}$/.test(run.head_sha) ||
(automatic && run.conclusion !== "success")) {
run.status !== "completed" || !/^[a-f0-9]{40}$/.test(run.head_sha)) {
throw new Error("Mirror artifacts must come from a completed main push in this repository's CI workflow");
}
// A legacy CI run may be red because its mirror failed after GitHub published.
// The published release, not that aggregate result, owns manual retry identity.
// A later publication step can fail after GitHub has published the packages.
// The matching stable release owns mirror identity, not the CI aggregate result.
const release = gh("releases/latest");
if (release.draft !== false || release.prerelease !== false || !isReleaseVersion(release.tag_name) ||
!/^[a-f0-9]{40}$/.test(release.target_commitish)) {
@@ -35,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,
+1 -1
View File
@@ -319,7 +319,7 @@ function Screen({ shot }: { shot: Shot }) {
<div className={viewer ? "lr-viewer-personal-controls" : "lr-host-personal-controls"}>
<div className={`lr-row-group lr-group-name ${viewer ? "lr-viewer-self-slot" : "lr-host-identity-slot"}`}>
<NameTag name={viewer ? names[0] : name} identity={viewer ? guests[0] : host} />
<Btn icon="pencil" cap="common.edit" title="host.nameEdit" hint="hint-rename" />
<Btn icon="pencil" cap="common.edit" collapsibleCaption title="host.nameEdit" hint="hint-rename" />
</div>
<div className={`lr-row-group lr-group-actions ${viewer ? "lr-viewer-actions-slot" : "lr-host-diagnostics-slot"}`}>
<Btn icon="gauge" cap="host.details" title="host.details.show" hint="hint-details" disabled={!live} />
+15 -14
View File
@@ -638,11 +638,12 @@
<p>
<span lang="en"
>Piik App is available for Windows, macOS, Linux and Android. Friends can watch in a computer or phone browser.
Physical-device coverage for the macOS and Linux apps is still limited; if you have a device,
we'd welcome your test results and <a href="https://github.com/TNTcraftHIM/Piik/issues">feedback</a>.</span
On iPhone/iPad, screen sharing requires Safari on iOS/iPadOS 27 or later and does not include system sound. Watching and camera sharing use the browser's existing capabilities; see the <a href="./docs/sharing.html?lang=en#iphone-and-ipad-screen-sharing">sharing guide</a>.
If something goes wrong, <a href="https://github.com/TNTcraftHIM/Piik/issues">let us know</a>.</span
><span lang="zh-CN"
>Piik App 提供 Windows、macOS、Linux 和 Android 版本,朋友可使用电脑或手机浏览器观看。
macOS 和 Linux 版 Piik App 仍需更多实机测试,欢迎有设备的朋友试用并<a href="https://github.com/TNTcraftHIM/Piik/issues">反馈问题</a>。</span
iPhone/iPad 屏幕分享需使用 iOS/iPadOS 27 及以上的 Safari,不包含系统声音;观看与摄像头分享使用浏览器已有能力,详见<a href="./docs/zh/sharing.html#iphone-与-ipad-屏幕分享">分享指南</a>。
遇到问题欢迎<a href="https://github.com/TNTcraftHIM/Piik/issues">反馈</a>。</span
>
</p>
</details>
@@ -745,19 +746,19 @@
</details>
<div class="faq-more">
<section aria-labelledby="faq-network-title">
<h3 id="faq-network-title"><span lang="en">Campus or restricted network?</span><span lang="zh-CN">校园网或受限网络?</span></h3>
<p><span lang="en">If direct connections fail, explore sites with media forwarding or a virtual LAN.</span><span lang="zh-CN">直连不通时,可尝试支持媒体转发的站点或虚拟局域网。</span></p>
<a class="text-link" lang="en" href="./docs/network.html?lang=en">Explore connection options<span aria-hidden="true"> ↗</span></a>
<a class="text-link" lang="zh-CN" href="./docs/zh/network.html">查看连接方案<span aria-hidden="true"> ↗</span></a>
<h3 id="faq-network-title"><span lang="en">Can't join a friend's room?</span><span lang="zh-CN">进不了朋友的房间?</span></h3>
<p><span lang="en">The page opens, but picture or voice won't connect? Check the browser and network.</span><span lang="zh-CN">网页能打开,但画面或语音连不上?检查浏览器与网络。</span></p>
<a class="text-link" lang="en" href="./docs/network.html?lang=en">Troubleshoot joining<span aria-hidden="true"> ↗</span></a>
<a class="text-link" lang="zh-CN" href="./docs/zh/network.html">排查连接问题<span aria-hidden="true"> ↗</span></a>
</section>
<section aria-labelledby="faq-help-title">
<h3 id="faq-help-title"><span lang="en">Another sharing problem?</span><span lang="zh-CN">其他分享或连接问题?</span></h3>
<p><span lang="en">Find steps for invitations, sharing failures, picture and sound.</span><span lang="zh-CN">按现象查找步骤:打不开邀请、无法分享、画面或声音异常。</span></p>
<a class="text-link" href="./docs/troubleshooting.html?lang=en" data-doc-page="troubleshooting.html">
<span lang="en">Open troubleshooting</span><span lang="zh-CN">查看问题排查</span><span aria-hidden="true"> ↗</span>
</a>
<h3 id="faq-help-title"><span lang="en">More questions?</span><span lang="zh-CN">更多问题</span></h3>
<p><span lang="en">Find help with sharing, sound, picture quality and remote control.</span><span lang="zh-CN">分享、声音、画质与远程控制,按遇到的问题查找。</span></p>
<a class="text-link" lang="en" href="./docs/troubleshooting.html?lang=en">Browse troubleshooting<span aria-hidden="true"> ↗</span></a>
<a class="text-link" lang="zh-CN" href="./docs/zh/troubleshooting.html">查看疑难解答<span aria-hidden="true"> ↗</span></a>
</section>
</div>
<p class="faq-feedback"><span lang="en">Still stuck? <a href="./docs/troubleshooting.html?lang=en#reporting-a-problem">Report a problem<span aria-hidden="true"> ↗</span></a></span><span lang="zh-CN">仍未解决?<a href="./docs/zh/troubleshooting.html#反馈问题">反馈问题<span aria-hidden="true"> ↗</span></a></span></p>
</div>
</section>
@@ -905,13 +906,13 @@
<p class="download-variant">iPhone / iPad</p>
<a class="lr-btn button download-button" href="https://demo.piik.tv"
><span lang="en">Use online</span><span lang="zh-CN">使用在线版</span><span aria-hidden="true">↗</span></a>
<p class="download-note"><span lang="en">Use Piik in your browser. No installation needed.</span><span lang="zh-CN">无需安装,在浏览器中直接使用。</span></p>
<p class="download-note"><span lang="en">Screen sharing requires Safari on iOS/iPadOS 27 or later.</span><span lang="zh-CN">屏幕分享需 iOS/iPadOS 27 及以上的 Safari。</span></p>
</article>
</div>
</section>
<div class="download-help">
<a class="lr-btn button" href="https://github.com/TNTcraftHIM/Piik"><span lang="en">View on GitHub</span><span lang="zh-CN">GitHub 项目</span><span aria-hidden="true"> ↗</span></a>
<p><span lang="en">Found a problem? <a href="https://github.com/TNTcraftHIM/Piik/issues">Let us know</a>.</span><span lang="zh-CN">遇到问题?欢迎<a href="https://github.com/TNTcraftHIM/Piik/issues">反馈</a>。</span></p>
<p><span lang="en">Need help? Start with <a href="./docs/troubleshooting.html?lang=en">troubleshooting</a>, or <a href="https://github.com/TNTcraftHIM/Piik/issues">report a problem</a>.</span><span lang="zh-CN">遇到问题?先看<a href="./docs/zh/troubleshooting.html">问题排查</a>,或向我们<a href="https://github.com/TNTcraftHIM/Piik/issues">反馈</a>。</span></p>
</div>
</section>
+2
View File
@@ -175,6 +175,8 @@ h3 { font-size: 21px; font-weight: 700; letter-spacing: -.03em; line-height: 1.3
.faq-more > section { display: flex; flex-direction: column; align-items: flex-start; gap: 10px; padding: 20px; border: 1px solid var(--line); border-radius: 18px; }
.faq-more h3 { color: var(--ink); font-size: 15px; font-weight: 650; }
.faq-more a { margin-top: auto; color: var(--ink); }
.faq-feedback { margin-top: 12px; color: var(--muted); font-size: 12px; }
.faq-feedback a { display: inline-block; padding-block: 8px; }
summary { display: flex; align-items: center; justify-content: space-between; gap: 20px; padding: 21px 0; font-size: 15px; font-weight: 650; list-style: none; }
summary::-webkit-details-marker { display: none; }
summary::after { content: "+"; flex: none; width: 22px; font-size: 21px; font-weight: 400; text-align: center; color: var(--action-text); }
@@ -98,6 +98,9 @@ export function FloatingPanel({ id, trigger, title, icon, compact = false, ancho
// resizing the living room or taking ownership of scrolling/focus.
const viewport = window.visualViewport;
const place = (change?: PanelChange) => {
// Native hiding/adoption can precede React's effect cleanup. Only this
// document's visible panel can update its remembered in-page position.
if (panel.ownerDocument !== document || !panel.matches(":popover-open")) return;
const layout = document.documentElement;
const width = viewport?.width ?? layout.clientWidth, height = viewport?.height ?? layout.clientHeight;
const maxWidth = Math.max(0, width - 24), maxHeight = Math.max(0, height - 24);
+5 -5
View File
@@ -85,7 +85,7 @@ const webVersion = import.meta.env.VITE_PIIK_VERSION ?? "development";
const webRelease = /^v\d+\.\d+\.\d+$/.test(webVersion)
? `https://github.com/TNTcraftHIM/Piik/releases/tag/${webVersion}` : null;
function BrowserHelpContent({ active }: { active: boolean }) {
function BrowserHelpContent({ active, diagnosticControl }: { active: boolean; diagnosticControl?: React.ReactNode }) {
const { lang, vis, t } = useCopy();
const guide = useProjectLink(`/docs/${lang === "zh" ? "zh/" : ""}troubleshooting.html`,
`https://github.com/TNTcraftHIM/Piik/blob/main/docs/guide/troubleshooting${lang === "zh" ? ".zh-CN" : ""}.md`, active);
@@ -101,13 +101,13 @@ function BrowserHelpContent({ active }: { active: boolean }) {
<Glyph name="book" size={16} />{!vis && <span className="lr-cap">{t("help.troubleshooting")}</span>}
</a>
</Tooltip>
<BrowserDiagnosticsButton size="compact" quiet />
{diagnosticControl === undefined ? <BrowserDiagnosticsButton size="compact" quiet /> : diagnosticControl}
</>}
</nav>
</div>;
}
function BrowserHelpMenu() {
function BrowserHelpMenu({ diagnosticControl }: { diagnosticControl?: React.ReactNode }) {
const { vis, t } = useCopy();
const id = useId();
const trigger = useRef<HTMLButtonElement>(null);
@@ -125,7 +125,7 @@ function BrowserHelpMenu() {
className="lr-anchored-card lr-help-menu" onToggle={event => {
if (event.target === event.currentTarget) setOpen(event.newState === "open");
}}>
<BrowserHelpContent active={open} />
<BrowserHelpContent active={open} diagnosticControl={diagnosticControl} />
</div>, document.body)}
</>;
}
@@ -198,7 +198,7 @@ export function HeaderControls({ diagnosticControl, appControl }: { diagnosticCo
{themeButton}
</Tooltip>
</div>
{diagnosticControl === undefined ? compact ? <BrowserHelpContent active={open} /> : <BrowserHelpMenu /> : diagnosticControl}
{compact ? <BrowserHelpContent active={open} diagnosticControl={diagnosticControl} /> : <BrowserHelpMenu diagnosticControl={diagnosticControl} />}
</div>
</div>
);
+17 -3
View File
@@ -1,5 +1,6 @@
import { useEffect, useId, useRef, useState, type ReactNode } from "react";
import { useCopy } from "../../ui/copy";
import { Glyph } from "../../ui/icons";
export function NumberControl({ value, min, max, step, unit, showUnit = true, name, label, disabled, onChange, className, children }: {
value: number;
@@ -19,6 +20,7 @@ export function NumberControl({ value, min, max, step, unit, showUnit = true, na
const [invalid, setInvalid] = useState(false);
const errorId = useId();
const input = useRef<HTMLInputElement>(null);
useEffect(() => { input.current!.value = String(value); }, [value]);
useEffect(() => setInvalid(false), [value, min, max, step]);
const reset = () => { input.current!.value = String(value); setInvalid(false); };
const select = (next: number) => {
@@ -26,8 +28,14 @@ export function NumberControl({ value, min, max, step, unit, showUnit = true, na
reset();
if (next !== value) onChange(next);
};
const number = <label className="lr-input lr-quality-number">
<input ref={input} type="number" inputMode={step < 1 ? "decimal" : "numeric"} name={name} key={value}
const adjust = (direction: number) => {
const field = input.current!;
if (direction > 0) field.stepUp(); else field.stepDown();
const valid = field.validity.valid && Number.isFinite(field.valueAsNumber);
if (valid) select(field.valueAsNumber); else setInvalid(true);
};
const number = <span className="lr-input lr-quality-number">
<input ref={input} type="number" inputMode={step < 1 ? "decimal" : "numeric"} name={name}
defaultValue={value} min={min} max={max} step={step} disabled={disabled} required aria-label={label}
aria-invalid={invalid || undefined} aria-describedby={invalid ? errorId : undefined}
onInput={() => setInvalid(false)}
@@ -40,7 +48,13 @@ export function NumberControl({ value, min, max, step, unit, showUnit = true, na
event.currentTarget.blur();
}} />
{showUnit && <span>{unit}</span>}
</label>;
<span className="lr-number-steppers" onPointerDown={event => event.preventDefault()}>
<button type="button" className="lr-btn is-dense is-quiet" disabled={disabled}
aria-label={t("common.increase", { name: label })} onClick={() => adjust(1)}><Glyph name="arrowUp" size={14} /></button>
<button type="button" className="lr-btn is-dense is-quiet" disabled={disabled}
aria-label={t("common.decrease", { name: label })} onClick={() => adjust(-1)}><Glyph name="arrowDown" size={14} /></button>
</span>
</span>;
return <div className={className} onBlur={event => {
if (event.currentTarget.contains(event.relatedTarget)) return;
const field = input.current!;
@@ -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}
+4
View File
@@ -45,6 +45,10 @@ button { -webkit-user-select: none; user-select: none; -webkit-touch-callout: no
.lr-btn > .lr-glyph { width: var(--button-icon-size, var(--control-icon-size)); height: var(--button-icon-size, var(--control-icon-size)); }
.lr-btn.is-compact { --button-size: var(--control-compact-size); --button-padding: 10px; }
.lr-btn.is-dense { --button-size: var(--control-dense-size); --button-padding: 8px; --button-icon-size: 16px; }
@container value-actions (max-width: 420px) {
.lr-btn[data-caption="collapsible"] { width: var(--button-size, var(--control-size)); padding-inline: 0; }
.lr-btn[data-caption="collapsible"] > .lr-cap { display: none; }
}
.lr-btn.is-quiet { border-radius: 12px; }
.lr-btn.is-quiet:not(.is-on):not(.is-primary):not(.is-danger) { background: transparent; border-color: transparent; color: var(--muted); box-shadow: none; }
.lr-btn.is-quiet:not(.is-on):not(.is-primary):not(.is-danger):is(:hover, :focus-visible):not(:disabled):not([aria-disabled="true"]) { background: var(--control-hover); border-color: transparent; color: var(--ink); }
+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; }
@@ -43,6 +43,7 @@ export function Btn({
id,
icon,
cap,
collapsibleCaption = false,
tone,
size,
quiet = false,
@@ -66,6 +67,8 @@ export function Btn({
id?: string;
icon: GlyphName;
cap?: CopyKey;
/** Auxiliary caption may yield space while its icon, label and hint remain. */
collapsibleCaption?: boolean;
tone?: "primary" | "danger" | "on";
size?: "compact" | "dense";
quiet?: boolean;
@@ -100,6 +103,7 @@ export function Btn({
id={id}
type={type}
className={`lr-btn${size ? ` is-${size}` : ""}${quiet ? " is-quiet" : ""}${activeTone ? ` is-${activeTone}` : ""}`}
data-caption={collapsibleCaption ? "collapsible" : undefined}
aria-label={label}
disabled={disabled && !softDisabled}
aria-disabled={softDisabled || undefined}
@@ -31,7 +31,10 @@ export function useAnchoredPopover(
const left = (viewport?.offsetLeft ?? 0) + 8, top = (viewport?.offsetTop ?? 0) + 8;
const right = left + (viewport?.width ?? view.innerWidth) - 16;
const bottom = top + (viewport?.height ?? view.innerHeight) - 16;
if (!anchor.getClientRects().length || rect.bottom < top || rect.top > bottom || rect.right < left || rect.left > right) {
const anchorOutside = rect.bottom < top || rect.top > bottom || rect.right < left || rect.left > right;
// A keyboard can cover the anchor while its popover still owns input.
// Keep that editing surface placed in view; a removed trigger still closes it.
if (!anchor.getClientRects().length || (anchorOutside && !menu.contains(menu.ownerDocument.activeElement))) {
menu.hidePopover();
return;
}
@@ -44,7 +47,7 @@ export function useAnchoredPopover(
const preferredHeight = Math.min(height, minVisibleHeight);
const openAbove = side === "above" ? above >= preferredHeight || above > below : below < preferredHeight && above > below;
const beside = openAbove ? above : below;
menu.style.maxHeight = `${Math.min(maxHeight, beside >= preferredHeight ? beside : bottom - top)}px`;
menu.style.maxHeight = `${Math.min(maxHeight, bottom - top, beside >= preferredHeight ? beside : bottom - top)}px`;
menu.classList.toggle("is-above", openAbove);
const x = align === "center" ? rect.left + (rect.width - menu.offsetWidth) / 2 : rect.right - menu.offsetWidth;
menu.style.left = `${Math.max(left, Math.min(x, right - menu.offsetWidth))}px`;
+1 -1
View File
@@ -80,7 +80,7 @@ export function parseMirrorReleaseMetadata(value: unknown, packageTarget?: strin
if (release.prerelease !== false || typeof release.body !== "string") return null;
const sources = [...release.body.matchAll(/^<!-- piik-source: ([0-9a-f]{40}) -->\r?$/gm)];
if (sources.length !== 1) return null;
// The mirror tag identifies its README commit, never the original Piik source.
// The mirror publisher records original source identity in this marker.
const normalized = parseReleaseMetadata({
tag_name: release.tag_name, html_url: RELEASE_PAGE + String(release.tag_name),
target_commitish: sources[0][1],
+2
View File
@@ -217,6 +217,8 @@ export const en: Record<CopyKey, string> = {
"notice.dismiss": "Dismiss notice",
"common.enable": "Enable {name}",
"common.disable": "Disable {name}",
"common.increase": "Increase {name}",
"common.decrease": "Decrease {name}",
"host.join.hide": "Hide room entry",
"host.advanced.hide": "Hide sharing settings",
"host.password.settingsHide": "Hide password settings",
+2
View File
@@ -217,6 +217,8 @@ export const zh = {
"notice.dismiss": "关闭提示",
"common.enable": "开启{name}",
"common.disable": "关闭{name}",
"common.increase": "增大{name}",
"common.decrease": "减小{name}",
"host.join.hide": "收起加入房间",
"host.advanced.hide": "收起分享设置",
"host.password.settingsHide": "收起密码设置",
+18
View File
@@ -0,0 +1,18 @@
/** Retire the caller immediately; a late permission grant still owns real tracks. */
export async function acquireMediaStream(start: () => Promise<MediaStream>, signal?: AbortSignal): Promise<MediaStream> {
signal?.throwIfAborted();
const pending = start();
return new Promise((resolve, reject) => {
const abort = () => { signal?.removeEventListener("abort", abort); reject(signal!.reason); };
signal?.addEventListener("abort", abort, { once: true });
if (signal?.aborted) abort();
pending.then(stream => {
signal?.removeEventListener("abort", abort);
if (signal?.aborted) stream.getTracks().forEach(track => track.stop());
else resolve(stream);
}, error => {
signal?.removeEventListener("abort", abort);
reject(error);
});
});
}
+14 -10
View File
@@ -1,6 +1,7 @@
import type { BrowserCaptureSource } from "./quality";
import { audioInputConstraints } from "./audio-capture";
import { MicrophoneInput } from "./microphone-input";
import { acquireMediaStream } from "./capture-stream";
export interface CommentaryInput { deviceId: string; volume: number; voiceProcessing: boolean }
@@ -14,7 +15,7 @@ export class HostAudio {
private sourceNode: MediaStreamAudioSourceNode | null = null;
private microphone: MicrophoneInput | null = null;
private microphoneNode: MediaStreamAudioSourceNode | null = null;
private microphoneRequest = 0;
private microphoneRequest: AbortController | null = null;
private closed = false;
constructor(private source: MediaStream, private kind: BrowserCaptureSource = "browser",
private availabilityChanged: (available: boolean) => void = () => {},
@@ -63,21 +64,22 @@ export class HostAudio {
}
}
async setMicrophone(enabled: boolean, settings: CommentaryInput): Promise<void> {
const request = ++this.microphoneRequest;
this.microphoneRequest?.abort();
this.microphoneRequest = null;
if (!enabled) { this.clearMicrophone(); return; }
if (!this.context || !this.destination || this.closed) throw new Error("Shared audio is unavailable");
const request = this.microphoneRequest = new AbortController();
const context = new AudioContext();
let stream: MediaStream | undefined, input: MicrophoneInput | undefined;
try {
const resumed = context.resume().then(() => true, () => false);
await this.context.resume();
stream = await navigator.mediaDevices.getUserMedia({ audio: { ...audioInputConstraints(settings.voiceProcessing),
...(settings.deviceId ? { deviceId: { exact: settings.deviceId } } : {}) }, video: false });
const resumed = Promise.all([context.resume(), this.context.resume()]).then(() => true, () => false);
stream = await acquireMediaStream(() => navigator.mediaDevices.getUserMedia({ audio: { ...audioInputConstraints(settings.voiceProcessing),
...(settings.deviceId ? { deviceId: { exact: settings.deviceId } } : {}) }, video: false }), request.signal);
if (!await resumed) throw new Error("Microphone audio could not start");
if (this.closed || request !== this.microphoneRequest) return;
request.signal.throwIfAborted();
if (!stream.getAudioTracks().some(track => track.readyState === "live")) throw new Error("No live microphone");
input = new MicrophoneInput(stream, context, settings.volume, () => {
if (this.microphone === input) { ++this.microphoneRequest; this.clearMicrophone(); }
if (this.microphone === input) { this.microphoneRequest?.abort(); this.clearMicrophone(); }
});
const node = this.context.createMediaStreamSource(input.stream);
node.connect(this.gain!);
@@ -87,8 +89,10 @@ export class HostAudio {
previousNode?.disconnect(); previousInput?.close();
this.microphoneChanged(true); this.reportAvailability();
} catch (error) {
input?.close(); throw error;
input?.close();
if (!request.signal.aborted) throw error;
} finally {
if (this.microphoneRequest === request) this.microphoneRequest = null;
if (!input) { stream?.getTracks().forEach(track => track.stop()); void context.close().catch(() => {}); }
}
}
@@ -119,7 +123,7 @@ export class HostAudio {
}
dispose(): void {
if (this.closed) return;
this.closed = true; ++this.microphoneRequest;
this.closed = true; this.microphoneRequest?.abort(); this.microphoneRequest = null;
this.unwatchSource();
this.clearMicrophone(); this.closeGraph();
this.source.getAudioTracks().forEach(track => track.stop());
+5 -2
View File
@@ -229,10 +229,13 @@ export function AppLauncherPage() {
const finish = beginStateChange();
setSiteBusy(true);
setSiteError(undefined);
const controller = new AbortController();
const timer = setTimeout(() => controller.abort(), 8_000);
async function save(setting: "site" | "startup-site"): Promise<boolean> {
const response = await fetch(`/api/client-launcher/${setting}`, {
method: "POST", headers: { "Content-Type": "application/json" },
body: JSON.stringify({ site: nextSite, ...(setting === "site" ? { allowed } : {}) }),
signal: controller.signal,
});
const result = launcherStateSchema.pick({ sites: true, startupSite: true }).safeParse(await response.json().catch(() => null));
if (result.success) {
@@ -251,7 +254,7 @@ export function AppLauncherPage() {
} catch {
setSiteError(t("client.connect.saveFailed"));
return false;
} finally { finish(); setSiteBusy(false); }
} finally { clearTimeout(timer); finish(); setSiteBusy(false); }
}
async function approveSite(site: string): Promise<void> {
@@ -264,7 +267,7 @@ export function AppLauncherPage() {
return (
<div className="lr-app">
<AppHeader homeHref="/client" diagnosticControl={appDebug === undefined ? null : (
<Btn icon="cpu" title="client.launch.debugHint" size="compact"
<Btn icon="cpu" title="client.launch.debugHint" cap="debug.start" size="compact" quiet
pressed={debug} tone={debug ? "on" : undefined} hint="debug-start"
disabled={appDebug || debugBusy || loading || starting || !!target || error?.kind === "load"}
onClick={() => void enableDebug()} />
+22 -2
View File
@@ -1,7 +1,7 @@
import { useLayoutEffect, useRef, useState } from "react";
import type { VideoFit, VideoRotation } from "../media/video-geometry";
import { BackButton, Btn, Chip, NameTag, Pill, SwitchItem } from "../components/living/primitives";
import { RoomChip, RoomCodePlaceholder, RoomAdmissionBadge } from "../components/living/RoomChip";
import { BackButton, Btn, Chip, FieldCap, NameTag, Pill, SwitchItem } from "../components/living/primitives";
import { Lcd, RoomChip, RoomCodePlaceholder, RoomAdmissionBadge } from "../components/living/RoomChip";
import { CaptureSourcePicker, type NativeSourceList } from "../components/living/CaptureSourcePicker";
import { LedStrip } from "../components/living/Header";
import { StageOverlay, StageTv } from "../components/living/Stage";
@@ -90,6 +90,7 @@ export function ControlsPreview() {
const [paused, setPaused] = useState(false);
const [passwordVisible, setPasswordVisible] = useState(false);
const [name, setName] = useState("Piik friend");
const [editingName, setEditingName] = useState(false);
const [invalid, setInvalid] = useState(false);
const [sourceOpen, setSourceOpen] = useState(displayPreview);
const [sourceRevision, setSourceRevision] = useState(0);
@@ -269,6 +270,25 @@ export function ControlsPreview() {
<label className="lr-input"><Glyph name="pencil" size={17} /><input value={name} aria-label={t("host.name")}
autoComplete="off" onChange={event => setName(event.target.value)} /></label>
</div>
{(["host", "viewer"] as const).map(role => <div key={role} className={`lr-row lr-${role}-summary-row`}>
<div className={`lr-row-group lr-${role}-room-slot`}><FieldCap k="common.roomCode" />
{role === "host" ? <RoomChip roomId="9527" onReplace={notify} /> : <Lcd code="9527" />}</div>
{role === "viewer" && <div className="lr-row-group lr-viewer-host-slot"><Glyph name="tv" size={17} />
<Tooltip overflow={{ text: name || "Piik friend", selector: "b" }} className="lr-name-hint"><b>{name || "Piik friend"}</b></Tooltip></div>}
<div className={`lr-row-group lr-group-name lr-${role === "host" ? "host-identity" : "viewer-self"}-slot`}>
{editingName ? <>
<span className="lr-input lr-name-editor"><input value={name} aria-label={t("host.name")}
onChange={event => setName(event.target.value)} /></span>
<Btn icon="check" title="host.nameSave" onClick={() => setEditingName(false)} />
<Btn icon="x" title="host.nameCancel" onClick={() => setEditingName(false)} />
</> : <><NameTag name={name || "Piik friend"} identity={`preview-${role}-name`} />
<Btn icon="pencil" cap="common.edit" collapsibleCaption title="host.nameEdit" hint="hint-rename" onClick={() => setEditingName(true)} /></>}
</div>
<div className={`lr-row-group lr-group-actions lr-${role === "host" ? "host-diagnostics" : "viewer-actions"}-slot`}>
<Btn icon="gauge" cap="host.details" title="host.details" onClick={notify} />
<Btn icon="network" cap="host.topology" title="host.topology.show" onClick={notify} />
</div>
</div>)}
<div className="cp-tools">
<label className="lr-input is-password"><Glyph name="key" size={17} /><input type={passwordVisible ? "text" : "password"}
placeholder={t("join.password")} aria-label={t("join.password")} aria-invalid={invalid} aria-describedby={invalid ? "preview-input-error" : undefined} autoComplete="off" />
+1
View File
@@ -4462,6 +4462,7 @@ export function HostPage({
<Btn
icon="pencil"
cap="common.edit"
collapsibleCaption
title="host.nameEdit"
hint="hint-rename"
onClick={() => {
+1
View File
@@ -2517,6 +2517,7 @@ export function ViewerPage({
key="edit-name"
icon="pencil"
cap="common.edit"
collapsibleCaption
title="host.nameEdit"
hint="hint-rename"
onClick={() => {
+9 -6
View File
@@ -783,6 +783,7 @@ body.lr-theater-open .lr-top { visibility: hidden; }
.lr-row.is-sub { background: var(--wall-2); border-color: transparent; }
.lr-row-group { display: flex; flex-wrap: wrap; align-items: center; gap: 10px; min-width: 0; }
.lr-group-actions { display: flex; flex-wrap: wrap; align-items: center; gap: 8px; min-width: 0; }
:is(.lr-host-summary-row, .lr-viewer-summary-row) { container: value-actions / inline-size; }
.lr-host-summary-row { justify-content: flex-end; column-gap: 8px; }
.lr-host-room-slot { margin-inline-end: auto; }
.lr-host-personal-controls,
@@ -1076,7 +1077,9 @@ body.lr-theater-open .lr-top { visibility: hidden; }
.lr-input:is(.lr-quality-number, .lr-video-size):has(:disabled) { opacity: .55; }
.lr-input:is(.lr-quality-number, .lr-video-size):has([aria-invalid="true"]) { border-color: var(--danger); }
.lr-quality-validation { color: color-mix(in srgb, var(--danger) 70%, var(--ink)); font-size: 12px; line-height: 1.5; }
.lr-input.lr-quality-number { width: 110px; gap: 6px; }
.lr-input.lr-quality-number { width: 144px; height: 52px; padding: 1px 3px 1px 10px; gap: 6px; }
.lr-number-steppers { display: flex; flex: none; flex-direction: column; }
.lr-number-steppers .lr-btn { --button-size: 24px; --button-padding: 0; --button-icon-size: 14px; --control-hover-transform: none; border-radius: 7px; }
.lr-quality-number input, .lr-video-size input { font-size: 13px; font-weight: 650; appearance: textfield; }
.lr-quality-number input { text-align: right; }
.lr-quality-number span, .lr-video-size span { color: var(--muted); font-size: 11px; }
@@ -1122,15 +1125,15 @@ body.lr-theater-open .lr-top { visibility: hidden; }
.lr-welcome-catalog li > span:first-child { display: block; }
.lr-welcome-catalog .lr-welcome-cipher { margin-top: 6px; }
.lr-input.lr-name-editor {
flex: 1;
min-width: 0;
width: 0;
flex: 1 1 224px;
min-width: min(160px, 100%);
width: 224px;
height: 40px;
border-radius: 999px;
}
.lr-group-name { width: 224px; max-width: 100%; }
.lr-group-name { width: max-content; max-width: 100%; }
.lr-group-name > [role="alert"] { flex-basis: 100%; }
.lr-group-name > .lr-name-hint { flex: 1; width: 0; }
.lr-group-name > .lr-name-hint { flex: 1 0 max-content; }
.lr-group-name .lr-name-tag { width: 100%; }
.lr-name-tag {
+74
View File
@@ -0,0 +1,74 @@
import { afterEach, describe, expect, it, vi } from "vitest";
import { useAnchoredPopover } from "../src/client/components/living/use-anchored-popover";
const hooks = vi.hoisted(() => ({ effects: [] as (() => void)[] }));
vi.mock("react", async importOriginal => ({
...await importOriginal<typeof import("react")>(),
useRef: (current: unknown) => ({ current }),
useLayoutEffect: (effect: () => (() => void) | undefined) => {
const cleanup = effect();
if (cleanup) hooks.effects.push(cleanup);
},
}));
vi.mock("../src/client/ui/panel-window", () => ({ useSurfaceDocument: () => undefined }));
afterEach(() => {
for (const cleanup of hooks.effects.splice(0).reverse()) cleanup();
vi.unstubAllGlobals();
});
function surface() {
const frame = new Map<number, FrameRequestCallback>();
let sequence = 0, visible = true, open = true;
const field = {};
const viewport = Object.assign(new EventTarget(), { width: 390, height: 844, offsetLeft: 0, offsetTop: 0 });
const view = Object.assign(new EventTarget(), {
visualViewport: viewport, innerWidth: 390, innerHeight: 844,
requestAnimationFrame: (callback: FrameRequestCallback) => { frame.set(++sequence, callback); return sequence; },
cancelAnimationFrame: (id: number) => { frame.delete(id); },
});
const owner = { defaultView: view, activeElement: null as unknown };
const anchor = {
getBoundingClientRect: () => ({ left: 40, right: 350, top: 600, bottom: 650, width: 310, height: 50 }),
getClientRects: () => visible ? [{}] : [],
closest: () => null,
};
const style: Record<string, string> = {};
const hidePopover = vi.fn(() => { open = false; });
const menu = Object.assign(new EventTarget(), {
ownerDocument: owner, style, classList: { toggle: vi.fn() }, scrollHeight: 700, offsetWidth: 300,
contains: (element: unknown) => element === field,
matches: () => open, hidePopover,
});
Object.defineProperty(menu, "offsetHeight", { get: () => Math.min(700, parseFloat(style.maxHeight) || 700) });
vi.stubGlobal("ResizeObserver", class { observe() {} disconnect() {} });
useAnchoredPopover({ current: anchor as unknown as HTMLElement }, { current: menu as unknown as HTMLElement });
const resize = (height: number) => {
viewport.height = height;
viewport.dispatchEvent(new Event("resize"));
for (const [id, callback] of [...frame]) { frame.delete(id); callback(0); }
};
return { owner, field, menu, style, hidePopover, resize, removeAnchor: () => { visible = false; } };
}
describe("Anchored popover input ownership", () => {
it("keeps an active editor open and inside the keyboard viewport", () => {
const current = surface();
current.owner.activeElement = current.field;
current.resize(320);
expect(current.hidePopover).not.toHaveBeenCalled();
expect(current.owner.activeElement).toBe(current.field);
expect(parseFloat(current.style.top!)).toBeGreaterThanOrEqual(8);
expect(parseFloat(current.style.top!) + parseFloat(current.style.maxHeight!)).toBeLessThanOrEqual(312);
current.removeAnchor();
current.resize(320);
expect(current.hidePopover).toHaveBeenCalledOnce();
});
it("still dismisses an inactive menu whose anchor leaves view", () => {
const current = surface();
current.resize(320);
expect(current.hidePopover).toHaveBeenCalledOnce();
});
});
+58 -6
View File
@@ -51,7 +51,7 @@ function mount(fetch: ReturnType<typeof vi.fn>, manualSite = false) {
state[name] = typeof value === "function" ? value(state[name]) : value;
})]));
const window = Object.assign(new EventTarget(), { location: { replace: vi.fn() } });
const timers = new Map<number, () => void>();
const timers = new Map<number, { callback: () => void; delay: number }>();
let nextTimer = 0;
const actions = runInNewContext(executable, {
...setters, z, fetch, window,
@@ -59,17 +59,26 @@ function mount(fetch: ReturnType<typeof vi.fn>, manualSite = false) {
siteBusy: false, debugBusy: false, starting: false, sites: saved.sites, manualSite, openOnApproval: false,
mode: "link", lang: "en", vis: false, debug: false, appDebug: false, localAccessPassword: "",
consoleLanguage: () => "en", launchURL: (target: string) => target, t: (key: string) => key,
AbortController,
setTimeout: (callback: () => void, delay: number) => {
expect(delay).toBe(750);
timers.set(++nextTimer, callback);
return nextTimer;
const id = ++nextTimer;
timers.set(id, { callback, delay });
return id;
},
clearTimeout: (id: number) => timers.delete(id),
}) as { cleanup(): void; changeSite(site: string, setting?: "site" | "startup-site", starAfterApproval?: boolean, allowed?: boolean): Promise<boolean>; approveSite(site: string): Promise<void>; enableDebug(): Promise<void>; launch(event: { preventDefault(): void }): Promise<void> };
return { state, setters, ...actions, navigate: window.location.replace, focus: () => window.dispatchEvent(new Event("focus")),
retry: () => {
expect(timers.size).toBe(1);
const [id, callback] = [...timers][0]!;
const entry = [...timers].find(([, timer]) => timer.delay === 750);
expect(entry).toBeDefined();
const [id, { callback }] = entry!;
timers.delete(id);
callback();
},
expireRequest: () => {
const entry = [...timers].find(([, timer]) => timer.delay > 750);
expect(entry).toBeDefined();
const [id, { callback }] = entry!;
timers.delete(id);
callback();
},
@@ -212,6 +221,49 @@ describe("App launcher state recovery", () => {
page.cleanup();
});
it("releases the approval page when saving a site never responds", async () => {
const fetch = vi.fn(async (_url: string, options?: { method?: string; signal?: AbortSignal }) => {
if (options?.method === "POST") return await new Promise<never>((_, reject) => {
options.signal?.addEventListener("abort", () => reject(new Error("request aborted")), { once: true });
});
return response();
});
const page = mount(fetch, true);
await settle();
const approval = page.approveSite("https://next.example");
await settle();
expect(page.state.SiteBusy).toBe(true);
page.expireRequest();
await approval;
expect(page.state).toMatchObject({ SiteBusy: false, SiteError: "client.connect.saveFailed" });
expect(page.navigate).not.toHaveBeenCalled();
fetch.mockResolvedValueOnce(response({ ...saved, sites: [...saved.sites, "https://next.example"] }));
await page.approveSite("https://next.example");
expect(page.navigate).toHaveBeenCalledWith("https://next.example/#piik-client=1");
expect(page.state.SiteBusy).toBe(false);
page.cleanup();
});
it("keeps committed approval when the startup preference body stalls", async () => {
const nextSite = "https://next.example";
const approved = { ...saved, sites: [...saved.sites, nextSite] };
const fetch = vi.fn(async (url: string, options?: { method?: string; signal?: AbortSignal }) => {
if (url.endsWith("/startup-site")) return { ...response(), json: () => new Promise<never>((_, reject) => {
options?.signal?.addEventListener("abort", () => reject(new Error("body aborted")), { once: true });
}) };
return response(options?.method === "POST" ? approved : saved);
});
const page = mount(fetch, true);
await settle();
const approval = page.changeSite(nextSite, "site", true);
await settle();
expect(page.state).toMatchObject({ Sites: approved.sites, StartupSite: "", SiteBusy: true });
page.expireRequest();
await expect(approval).resolves.toBe(false);
expect(page.state).toMatchObject({ Sites: approved.sites, StartupSite: "", SiteBusy: false, SiteError: "client.connect.saveFailed" });
page.cleanup();
});
it("restores saved choices after a failed first read, then preserves unsaved edits on focus", async () => {
const fetch = vi.fn(async () => response()).mockRejectedValueOnce(new Error("unavailable"));
const page = mount(fetch);
+5 -1
View File
@@ -119,8 +119,12 @@ test("ending a share retires microphone permission completed after disposal", as
const audio = new HostAudio(media(new Track("video")), "browser", () => {}, enabled);
await audio.start();
const pending = audio.setMicrophone(true, { deviceId: "", volume: 1, voiceProcessing: true });
expect(getUserMedia).toHaveBeenCalledOnce();
audio.dispose();
await pending;
expect(contexts.every(context => context.state === "closed")).toBe(true);
complete(media(microphone));
await Promise.resolve();
audio.dispose(); complete(media(microphone)); await pending;
expect(microphone.stop).toHaveBeenCalledOnce();
expect(enabled).not.toHaveBeenCalledWith(true);
expect(contexts.every(context => context.state === "closed")).toBe(true);
+61 -1
View File
@@ -32,7 +32,7 @@ const source = ts.createSourceFile("HostPage.tsx", readFileSync(
new URL("../src/client/pages/HostPage.tsx", import.meta.url), "utf8",
), ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX);
const owners = new Set(["changeQuality", "commitQuality", "rememberQuality", "loadAppQualityPreference", "handleSignalMessage",
"switchSource", "watchCaptureEnd", "switchNativeSource", "switchToNativeSource", "createBrowserAudio", "retireNativeSenderPeers", "finishSourceSwitch", "replaceBrowserStream", "recoverBrowserFanout", "disposeNativeShare",
"switchSource", "watchCaptureEnd", "switchNativeSource", "switchToNativeSource", "createBrowserAudio", "changeCommentary", "retireNativeSenderPeers", "finishSourceSwitch", "replaceBrowserStream", "recoverBrowserFanout", "disposeNativeShare",
"acquireNativeClient", "requestSharing", "nativeCaptureCodec", "startNativeShare", "startBrowserNativeIngress",
"createNativePreview", "failNativePreview", "reconnectNativePreview", "reportHostChildFailure", "hostChildIsAssigned", "prepareHostChild",
"connectNativeClient", "handleNativeClientClosed", "releaseUnusedNativeClient", "closeCaptureSourcePicker",
@@ -338,6 +338,66 @@ describe("Camera replacement ownership", () => {
return { ...current, nativeControl, remoteSnapshot, picture, previous, camera, nativeStream, oldBridge, peer, nativePeer, startedPeerStreams, replacePublication };
}
it("releases pending Browser commentary when Native handoff retires its audio owner", async () => {
const current = sourceFixture(false);
const permission = deferred<MediaStream>();
const getUserMedia = vi.fn(() => permission.promise), contexts: { close: ReturnType<typeof vi.fn> }[] = [];
const outputAudio = { readyState: "live", stop: vi.fn() };
vi.stubGlobal("AudioContext", class {
close = vi.fn(async () => {});
resume = vi.fn(async () => {});
constructor() { contexts.push(this); }
createMediaStreamDestination() { return { stream: { getAudioTracks: () => [outputAudio], getTracks: () => [outputAudio] } }; }
createGain() { return { gain: { value: 1 }, connect() {}, disconnect() {} }; }
});
vi.stubGlobal("MediaStream", class {
constructor(private tracks: unknown[]) {}
getTracks() { return this.tracks; }
getVideoTracks() { return this.tracks.filter(track => track === current.previous.video); }
getAudioTracks() { return this.tracks.filter(track => track === outputAudio); }
});
vi.stubGlobal("navigator", { mediaDevices: { getUserMedia } });
let busy = false;
const setCommentaryBusy = vi.fn((value: boolean) => { busy = value; });
const setMicrophone = vi.fn(async () => {});
Object.assign(current.client, { setMicrophone });
Object.assign(current.context, {
commentaryOperationRef: ref(null), setCommentaryBusy, setCommentaryInput: vi.fn(),
commentaryInput: { deviceId: "", volume: 1, voiceProcessing: true },
startPeer: current.startChild,
});
const audio = current.context.hostAudioRef.current as HostAudio;
const disposed = vi.spyOn(audio, "dispose");
const lateTrack = { stop: vi.fn() };
try {
await audio.start();
const commentary = current.context.changeCommentary(true) as Promise<void>;
await vi.waitFor(() => expect(getUserMedia).toHaveBeenCalledOnce());
expect(busy).toBe(true);
// The normal source action is available while microphone permission waits.
await current.context.switchToNativeSource({ kind: "native", client: current.client,
target: { kind: "display", sourceId: "1", title: "Display" }, audio: false, path: {} });
expect(current.nativeModeRef.current).toBe(true);
expect(current.context.streamRef.current).toBe(current.nativeStream);
expect(disposed).toHaveBeenCalledOnce();
await vi.waitFor(() => expect(busy).toBe(false));
await commentary;
expect(contexts.every(context => context.close.mock.calls.length === 1)).toBe(true);
await current.context.changeCommentary(true);
expect(setMicrophone).toHaveBeenCalledExactlyOnceWith("native-source-2", true, 1, "");
permission.resolve({ getTracks: () => [lateTrack] } as unknown as MediaStream);
await Promise.resolve();
expect(lateTrack.stop).toHaveBeenCalledOnce();
expect(current.context.streamRef.current).toBe(current.nativeStream);
expect(current.context.endSharing).not.toHaveBeenCalled();
expect(current.createRoom).not.toHaveBeenCalled();
} finally {
permission.resolve({ getTracks: () => [lateTrack] } as unknown as MediaStream);
audio.dispose();
vi.unstubAllGlobals();
}
});
it.each(["initial", "replacement"])("rejects Browser capture that ends during %s audio preparation", async entry => {
const current = sourceFixture(entry === "replacement");
const pending = deferred<void>();
+31 -11
View File
@@ -16,7 +16,7 @@ const servers = [...linuxServers, {
}];
type Scenario = { existing?: boolean; draft?: boolean; badArchive?: boolean;
wrongSource?: boolean; wrongImage?: boolean; remoteMismatch?: boolean;
registryError?: boolean; newerRelease?: boolean; largeCommit?: boolean;
registryError?: string; newerRelease?: boolean; largeCommit?: boolean;
partial?: boolean; wrongPlatform?: boolean; attestation?: boolean; unknownPlatform?: boolean };
async function publish(options: Scenario = {}) {
@@ -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)
@@ -64,17 +70,28 @@ async function publish(options: Scenario = {}) {
} } }]);
}
if (args[0] === "manifest") {
if (options.registryError || !manifests.has(args[2])) {
// Docker CLI rebuilds a manifest list without its OCI annotations.
const original = manifests.get(args[2]) as { manifests?: object[] } | undefined;
return JSON.stringify({ ...original, manifests: original?.manifests?.map(entry => ({ ...entry, annotations: undefined })) });
}
if (args[0] === "buildx" && args[2] === "inspect") {
expect(args.slice(0, 4)).toEqual(["buildx", "imagetools", "inspect", "--raw"]);
const reference = args[4];
if (options.registryError || !manifests.has(reference)) {
throw Object.assign(new Error("Registry failure"), {
stderr: options.registryError ? "unauthorized: authentication required" : "manifest unknown",
stderr: options.registryError ?? `ERROR: ${reference}: not found`,
});
}
return JSON.stringify(manifests.get(args[2]));
return JSON.stringify(manifests.get(reference));
}
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] === "pull") images.set(args[3], args[2].slice("linux/".length));
if (args[0] === "tag") images.set(args[2], images.get(args[1])!);
if (args[0] === "push") manifests.set(args[1], {});
if (args[0] === "buildx") manifests.set(args[4], index);
if (args[0] === "buildx" && args[2] === "create") manifests.set(args[4], index);
return "{}";
});
const argv = process.argv;
@@ -85,7 +102,7 @@ async function publish(options: Scenario = {}) {
}
const pushes = () => command.mock.calls.filter(([program, args]) => program === "docker" && args[0] === "push")
.map(([, args]) => args[1]);
const indexes = () => command.mock.calls.filter(([program, args]) => program === "docker" && args[0] === "buildx")
const indexes = () => command.mock.calls.filter(([program, args]) => program === "docker" && args[0] === "buildx" && args[2] === "create")
.map(([, args]) => args.slice(4));
describe("container publication", () => {
@@ -107,7 +124,10 @@ describe("container publication", () => {
});
it.each([
{ draft: true }, { badArchive: true }, { wrongSource: true }, { wrongImage: true },
{ registryError: true }, { existing: true, remoteMismatch: true },
{ registryError: "unauthorized: authentication required" },
{ registryError: "ERROR: failed to fetch manifest sha256:missing: not found" },
{ registryError: "ERROR: lookup ghcr.io: i/o timeout" },
{ existing: true, remoteMismatch: true },
{ partial: true, remoteMismatch: true }, { wrongPlatform: true },
])("blocks invalid publication before pushing (%j)", async (options) => {
await expect(publish(options)).rejects.toThrow();
+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();
+2 -2
View File
@@ -29,7 +29,7 @@ function editor() {
const setInvalid = vi.fn();
const render = runInNewContext(executable, {
exports: {}, require: () => jsxRuntime, useRef: () => ({ current: input }), Number,
useState: () => [false, setInvalid], useId: () => "validation", useCopy: () => ({ t: vi.fn() }),
useState: () => [false, setInvalid], useId: () => "validation", useCopy: () => ({ t: vi.fn() }), Glyph: () => null,
useEffect: (effect: () => void) => effect(),
});
let choose!: (next: number) => void;
@@ -95,7 +95,7 @@ describe("Numeric quality editing group", () => {
expect(fields[index]).toContain(`value="${value}"`);
expect(fields[index]).not.toContain('type="range"');
expect(fields[index]).toContain('class="lr-quality-custom"');
if (nearest === null) expect(fields[index]).not.toContain('<button');
if (nearest === null) expect(fields[index]).not.toContain('class="lr-btn is-dense"');
else expect(fields[index]).toMatch(new RegExp(`<button[^>]*aria-label="[^"]*${nearest} ${unit}`));
}
expect(onChange).not.toHaveBeenCalled();
+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(); }
});
+13 -4
View File
@@ -25,13 +25,20 @@ 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);
expect(resolveMirrorSource("12345")).toEqual(expected);
api({ ...run, conclusion: "failure" });
expect(resolveMirrorSource("12345")).toEqual(expected);
expect(() => resolveMirrorSource("12345", true)).toThrow(/completed main push/);
expect(resolveMirrorSource("12345", true)).toEqual(expected);
});
it.each(["", "012345", "1e3", "-1", "12345\nmirror=true", "9007199254740992", undefined])
@@ -52,9 +59,11 @@ describe("mirror source authority", () => {
});
it("skips automatic runs without a current release and refuses an explicit stale retry", () => {
api(run, { ...release, target_commitish: "b".repeat(40) });
expect(resolveMirrorSource("12345", true)).toBeNull();
expect(() => resolveMirrorSource("12345")).toThrow(/does not match the latest/);
for (const conclusion of ["success", "failure", "cancelled"]) {
api({ ...run, conclusion }, { ...release, target_commitish: "b".repeat(40) });
expect(resolveMirrorSource("12345", true)).toBeNull();
expect(() => resolveMirrorSource("12345")).toThrow(/does not match the latest/);
}
});
it.each([{ draft: true }, { prerelease: true }, { tag_name: "preview" }, { target_commitish: "main" }])